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,47 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import res_partner
from . import res_users
from . import res_company
from . import account
from . import account_report
from . import account_report_snapshot
from . import account_analytic_report
from . import bank_reconciliation_report
from . import account_general_ledger
from . import account_generic_tax_report
from . import account_journal_group
from . import account_journal_report
from . import account_cash_flow_report
from . import account_deferred_reports
from . import account_multicurrency_revaluation_report
from . import account_move_line
from . import account_analytic_line
from . import account_trial_balance_report
from . import account_aged_partner_balance
from . import account_partner_ledger
from . import res_config_settings
from . import account_journal_dashboard
from . import ir_actions
from . import ir_ui_menu
from . import account_sales_report
from . import account_move
from . import account_tax
from . import executive_summary_report
from . import budget
from . import balance_sheet
from . import account_fiscal_position
from . import account_customer_statement
from . import account_followup_report
from . import account_return
from . import mail_thread
from . import mail_activity
from . import mail_message
from . import mail_scheduled_message
from . import account_audit_account_status
from . import kpi_provider
from . import ir_module
from . import account_chart_template
from . import account_journal
from . import account_lock_exception
from . import interco_comparison_report

View File

@@ -0,0 +1,249 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from ast import literal_eval
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.tools import SQL, html2plaintext
from odoo.addons.account.models.account_move import REVIEW_STATE_SELECTION
class AccountAccount(models.Model):
_inherit = "account.account"
exclude_provision_currency_ids = fields.Many2many('res.currency', relation='account_account_exclude_res_currency_provision', help="Whether or not we have to make provisions for the selected foreign currencies.")
budget_item_ids = fields.One2many(comodel_name='account.report.budget.item', inverse_name='account_id') # To use it in the domain when adding accounts from the report
audit_debit = fields.Monetary(string="Debit", compute="_compute_audit_period", currency_field="company_currency_id", compute_sql="_compute_sql_audit_debit", compute_sudo=False)
audit_credit = fields.Monetary(string="Credit", compute="_compute_audit_period", currency_field="company_currency_id", compute_sql="_compute_sql_audit_credit", compute_sudo=False)
audit_balance = fields.Monetary(string="Balance", compute="_compute_audit_period", currency_field="company_currency_id", compute_sql="_compute_sql_audit_balance", compute_sudo=False)
audit_balance_show_warning = fields.Boolean(compute="_compute_audit_balance_show_warning")
audit_previous_balance = fields.Monetary(string="Balance N-1", compute="_compute_audit_period", currency_field="company_currency_id", compute_sql="_compute_sql_audit_previous_balance", compute_sudo=False)
audit_previous_balance_show_warning = fields.Boolean(compute="_compute_audit_previous_balance_show_warning")
audit_var_n_1 = fields.Monetary(string="Var N-1", compute="_compute_audit_variation", currency_field="company_currency_id", compute_sql="_compute_sql_audit_var_n_1", compute_sudo=False)
audit_var_percentage = fields.Float(string="Var %", compute="_compute_audit_variation", compute_sql="_compute_sql_audit_var_percentage", compute_sudo=False)
audit_status = fields.Selection(selection=REVIEW_STATE_SELECTION, string="Status", compute="_compute_audit_status", inverse="_inverse_audit_status", compute_sql="_compute_sql_audit_status", compute_sudo=False)
account_status = fields.One2many(string="Account Status", comodel_name='account.audit.account.status', inverse_name='account_id')
last_message = fields.Char(string="Last Comment", compute='_compute_last_message')
@api.depends_context('working_file_id')
def _compute_audit_period(self):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
found_ids = set()
if working_file and any(self._ids):
query = self._as_query(ordered=False)
for account_id, debit, credit, balance, previous_balance in self.env.execute_query(query.select(*(
query.table[field_name]
for field_name in ('id', 'audit_debit', 'audit_credit', 'audit_balance', 'audit_previous_balance')
))):
account = self.browse(account_id)
account.audit_debit = debit
account.audit_credit = credit
account.audit_balance = balance
account.audit_previous_balance = previous_balance
found_ids.add(account_id)
remaining = self - self.browse(found_ids)
remaining.audit_debit = remaining.audit_credit = remaining.audit_balance = remaining.audit_previous_balance = 0
@api.model
def _common_audit_aml_sql(self, table, column_name, previous=False):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
if not working_file:
return SQL("NULL")
self.env['account.move.line'].flush_model(['debit', 'credit', 'balance', 'account_id', 'company_id', 'date', 'parent_state'])
# build the result and check if need to add the join
alias_audit = table._make_alias(f"audit_wf{working_file.id}{'p' if previous else ''}")
sql_result = SQL("COALESCE(%s, 0.0)", alias_audit[column_name])
if alias_audit._alias in table._query._joins:
return sql_result
# get dates
company_ids = working_file.company_ids.ids
if previous:
date_from, date_to = working_file.type_id._get_period_boundaries(
working_file.company_id, (working_file.date_from or fields.Date.context_today(self)) - relativedelta(days=1))
else:
date_from = working_file.date_from
date_to = working_file.date_to
table._query.add_join(
'LEFT JOIN',
alias_audit,
SQL("""
(SELECT
SUM(aml.debit) as debit,
SUM(aml.credit) as credit,
SUM(aml.balance) as balance,
account_id
FROM (
SELECT aml.debit, aml.credit, aml.balance, aml.account_id
FROM account_move_line aml
JOIN account_account aml_account ON aml_account.id = aml.account_id
WHERE aml.date <= %(date_to)s
AND NOT aml_account.account_type ILIKE ANY(ARRAY['income%%', 'expense%%', 'equity_unaffected'])
AND aml.company_id = ANY(%(company_ids)s)
AND aml.parent_state = 'posted'
UNION ALL
SELECT aml.debit, aml.credit, aml.balance, aml.account_id
FROM account_move_line aml
JOIN account_account aml_account ON aml_account.id = aml.account_id
WHERE aml.date <= %(date_to)s
AND aml.date >= %(date_from)s
AND aml_account.account_type ILIKE ANY(ARRAY['income%%', 'expense%%', 'equity_unaffected'])
AND aml.company_id = ANY(%(company_ids)s)
AND aml.parent_state = 'posted'
) aml
GROUP BY account_id)
""",
date_from=date_from,
date_to=date_to,
company_ids=company_ids,
),
SQL("%s = %s", alias_audit.account_id, table.id)
)
return sql_result
def _compute_sql_audit_debit(self, table):
return self._common_audit_aml_sql(table, 'debit')
def _compute_sql_audit_credit(self, table):
return self._common_audit_aml_sql(table, 'credit')
def _compute_sql_audit_balance(self, table):
return self._common_audit_aml_sql(table, 'balance')
def _compute_sql_audit_previous_balance(self, table):
return self._common_audit_aml_sql(table, 'balance', previous=True)
@api.depends('audit_balance', 'audit_previous_balance')
def _compute_audit_variation(self):
for account in self:
account.audit_var_n_1 = account.audit_balance - account.audit_previous_balance
if self.env.company.currency_id.is_zero(account.audit_previous_balance):
account.audit_var_percentage = False
else:
account.audit_var_percentage = (account.audit_balance - account.audit_previous_balance) / account.audit_previous_balance
def _compute_sql_audit_var_n_1(self, table):
balance_sql = self._compute_sql_audit_balance(table)
prev_balance_sql = self._compute_sql_audit_previous_balance(table)
return SQL("%s - %s", balance_sql, prev_balance_sql)
def _compute_sql_audit_var_percentage(self, table):
balance_sql = self._compute_sql_audit_balance(table)
prev_balance_sql = self._compute_sql_audit_previous_balance(table)
return SQL("CASE WHEN %(prev)s <> 0 THEN (%(curr)s - %(prev)s) / %(prev)s * 100 END", curr=balance_sql, prev=prev_balance_sql)
@api.depends_context('working_file_id')
def _compute_audit_status(self):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
self.audit_status = 'todo'
if working_file:
create_vals = []
account_status_by_account = {status.account_id: status for status in working_file.audit_account_status_ids}
for account in self:
if account in account_status_by_account:
account.audit_status = account_status_by_account[account].status
else:
create_vals.append({
'account_id': account.id,
'audit_id': working_file.id,
})
if create_vals:
self.env['account.audit.account.status'].create(create_vals)
def _compute_sql_audit_status(self, table):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
status_model = self.env['account.audit.account.status']
status_query = status_model._search([('audit_id', 'in', working_file.ids)])
if status_query.is_empty():
return SQL("NULL::text")
status_alias = table._make_alias('audit_status')
table._query.add_join(
'LEFT JOIN',
status_alias,
status_query.subselect(status_query.table.account_id, status_query.table.status),
SQL("%s = %s", status_alias.account_id, table.id)
)
return SQL('%s', status_alias.status)
def _inverse_audit_status(self):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
if working_file:
account_status_by_account = {status.account_id: status for status in working_file.audit_account_status_ids}
for account in self:
if account in account_status_by_account:
account_status_by_account[account].status = account.audit_status
def _compute_balance_warning(self, balance_field_name, warning_field_name):
for account in self:
if account.internal_group == 'asset':
account[warning_field_name] = account.company_currency_id.compare_amounts(account[balance_field_name], 0) == -1
elif account.internal_group == 'liability':
account[warning_field_name] = account.company_currency_id.compare_amounts(account[balance_field_name], 0) == 1
else:
account[warning_field_name] = False
@api.depends('audit_balance')
def _compute_audit_balance_show_warning(self):
self._compute_balance_warning('audit_balance', 'audit_balance_show_warning')
@api.depends('audit_previous_balance')
def _compute_audit_previous_balance_show_warning(self):
self._compute_balance_warning('audit_previous_balance', 'audit_previous_balance_show_warning')
@api.depends_context('working_file_id')
def _compute_last_message(self):
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
if not working_file:
for account in self:
account.last_message = False
return
self.env['mail.message'].flush_model(['model', 'res_id', 'body'])
self.env['account.report.annotation'].flush_model(['message_id'])
self.env.cr.execute("""
SELECT DISTINCT ON (message.res_id) message.res_id, message.body
FROM mail_message message
JOIN account_report_annotation annotation ON annotation.message_id = message.id
WHERE message.model = 'account.account' AND message.res_id = ANY(%s) AND annotation.date >= %s AND annotation.date <= %s
ORDER BY message.res_id, message.create_date DESC
""", (self.ids, working_file.date_from, working_file.date_to))
last_message_by_account = {
row[0]: html2plaintext(row[1])
for row in self.env.cr.fetchall()
}
for account in self:
account.last_message = last_message_by_account.get(account.id, False)
def action_audit_account(self):
action = self.env['ir.actions.act_window']._for_xml_id("account.action_account_moves_all")
context = literal_eval(action.get('context', {}))
working_file = self.env['account.return'].browse(self.env.context.get('working_file_id'))
if working_file:
context.update({
'search_default_audit_date_between': 1,
'date_to': fields.Date.to_string(working_file.date_to),
'date_from': fields.Date.to_string(working_file.date_from),
})
return {
**action,
'domain': [('account_id', 'in', self.ids)],
'context': context,
'search_view_id': self.env.ref('account_reports.view_audit_move_line_filter').id,
'views': [(self.env.ref('account_reports.view_audit_move_line_list').id, 'list')],
}

View File

@@ -0,0 +1,449 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from dateutil.relativedelta import relativedelta
from odoo import _, fields, models
from odoo.tools import SQL
class AccountAgedPartnerBalanceReportHandler(models.AbstractModel):
_name = 'account.aged.partner.balance.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Aged Partner Balance Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
hidden_columns = set()
options['multi_currency'] = report.env.user.has_group('base.group_multi_currency')
options['show_currency'] = options['multi_currency'] and (previous_options or {}).get('show_currency', False)
options['no_xlsx_currency_code_columns'] = True
if not options['show_currency']:
hidden_columns.update(['amount_currency', 'currency'])
options['show_account'] = (previous_options or {}).get('show_account', False)
if not options['show_account']:
hidden_columns.add('account_name')
options['columns'] = [
column for column in options['columns']
if column['expression_label'] not in hidden_columns
]
default_order_column = {
'expression_label': 'invoice_date',
'direction': 'ASC',
}
options['order_column'] = previous_options.get('order_column') or default_order_column
options['aging_based_on'] = previous_options.get('aging_based_on') or 'base_on_maturity_date'
options['aging_interval'] = previous_options.get('aging_interval') or 30
# Set aging column names
interval = options['aging_interval']
for column in options['columns']:
if column['expression_label'].startswith('period'):
period_number = int(column['expression_label'].replace('period', '')) - 1
if 0 <= period_number < 4:
column['name'] = f'{interval * period_number + 1}-{interval * (period_number + 1)}'
options['custom_display_config'] = {
'css_custom_class': 'aged_partner_balance',
'templates': {
'AccountReportLineName': 'account_reports.AgedPartnerBalanceLineName',
},
'components': {
'AccountReportFilters': 'AgedPartnerBalanceFilters',
},
}
def _custom_line_postprocessor(self, report, options, lines):
partner_lines_map = {}
# Sort line dicts by partner
for line in lines:
model, model_id = report._get_model_info_from_id(line.id)
if model == 'res.partner' and model_id:
partner_lines_map[model_id] = line
if partner_lines_map:
for partner, line_data in zip(
self.env['res.partner'].browse(partner_lines_map),
partner_lines_map.values()
):
line_data.get_custom()['trust'] = partner.with_company(partner.company_id or self.env.company).trust
return lines
def _report_engine_aged_receivable(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._aged_partner_report_custom_engine_common(options, 'asset_receivable', current_groupby, formulas_dict)
def _report_engine_aged_payable(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._aged_partner_report_custom_engine_common(options, 'liability_payable', current_groupby, formulas_dict)
def _aged_partner_report_custom_engine_common(self, options, internal_type, current_groupby, formulas_dict):
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
def minus_days(date_obj, days):
return fields.Date.to_string(date_obj - relativedelta(days=days))
aging_date_field = SQL.identifier('invoice_date') if options['aging_based_on'] == 'base_on_invoice_date' else SQL.identifier('date_maturity')
date_to = fields.Date.from_string(options['date']['date_to'])
interval = options['aging_interval']
periods = [(False, fields.Date.to_string(date_to))]
# Since we added the first period in the list we have to do one less iteration
nb_column_groups = len(options['column_groups'])
nb_periods = len([column for column in options['columns'] if column['expression_label'].startswith('period')]) // nb_column_groups - 1
for i in range(nb_periods):
start_date = minus_days(date_to, (interval * i) + 1)
# The last element of the list will have False for the end date
end_date = minus_days(date_to, interval * (i + 1)) if i < nb_periods - 1 else False
periods.append((start_date, end_date))
def build_result_dict(report, query_res_lines):
rslt = {f'period{i}': 0 for i in range(len(periods))}
for query_res in query_res_lines:
for i in range(len(periods)):
period_key = f'period{i}'
rslt[period_key] += query_res[period_key]
if current_groupby == 'id':
query_res = query_res_lines[0] # We're grouping by id, so there is only 1 element in query_res_lines anyway
currency = self.env['res.currency'].browse(query_res['currency_id'][0]) if len(query_res['currency_id']) == 1 else None
rslt.update({
'invoice_date': query_res['invoice_date'][0] if len(query_res['invoice_date']) == 1 else None,
'due_date': query_res['due_date'][0] if len(query_res['due_date']) == 1 else None,
'amount_currency': query_res['amount_currency'],
'currency_id': query_res['currency_id'][0] if len(query_res['currency_id']) == 1 else None,
'currency': currency.display_name if currency else None,
'account_name': query_res['account_name'][0] if len(query_res['account_name']) == 1 else None,
'total': None,
'has_sublines': True,
# Needed by the custom_unfold_all_batch_data_generator, to speed-up unfold_all
'partner_id': query_res['partner_id'][0] if query_res['partner_id'] else None,
})
else:
rslt.update({
'invoice_date': None,
'due_date': None,
'amount_currency': None,
'currency_id': None,
'currency': None,
'account_name': None,
'total': sum(rslt[f'period{i}'] for i in range(len(periods))),
'has_sublines': True,
})
return rslt
# Build period table
period_table = SQL('(VALUES %s)', SQL(',').join(
SQL("(%s, %s, %s)", from_ or None, to or None, i)
for i, (from_, to) in enumerate(periods))
)
# Build query
if not report._get_option_recon_date(options):
# Ensure the residual is computed at the report date_to
options['recon_date'] = {
'date_to': options['date']['date_to'],
}
query = report._get_report_query(options, 'strict_range', domain=[('account_id.account_type', '=', internal_type)])
account_code = query.table._sudo().account_id.code
always_present_groupby = SQL("period_table.period_index")
if current_groupby:
groupby_field_sql = query.table[current_groupby]
select_from_groupby = SQL("%s AS grouping_key,", groupby_field_sql)
groupby_clause = SQL("%s, %s", groupby_field_sql, always_present_groupby)
else:
select_from_groupby = SQL()
groupby_clause = always_present_groupby
multiplicator = -1 if internal_type == 'liability_payable' else 1
select_period_query = SQL(',').join(
SQL("""
CASE WHEN period_table.period_index = %(period_index)s
THEN %(multiplicator)s * SUM(%(balance_select)s)
ELSE 0 END AS %(column_name)s
""",
period_index=i,
multiplicator=multiplicator,
column_name=SQL.identifier(f"period{i}"),
balance_select=SQL("%s * %s", query.table.residual_at_date, query.table.consolidation_rate),
)
for i in range(len(periods))
)
query = SQL(
"""
WITH period_table(date_start, date_stop, period_index) AS (%(period_table)s)
SELECT
%(select_from_groupby)s
%(multiplicator)s * SUM(%(residual_currency_at_date)s) AS amount_currency,
ARRAY_AGG(DISTINCT account_move_line.partner_id) AS partner_id,
ARRAY_AGG(account_move_line.payment_id) AS payment_id,
ARRAY_AGG(DISTINCT COALESCE(account_move_line.invoice_date, account_move_line.date)) AS invoice_date,
ARRAY_AGG(DISTINCT COALESCE(account_move_line.%(aging_date_field)s, account_move_line.date)) AS report_date,
ARRAY_AGG(DISTINCT %(account_code)s) AS account_name,
ARRAY_AGG(DISTINCT COALESCE(account_move_line.%(aging_date_field)s, account_move_line.date)) AS due_date,
ARRAY_AGG(DISTINCT account_move_line.currency_id) AS currency_id,
COUNT(account_move_line.id) AS aml_count,
ARRAY_AGG(%(account_code)s) AS account_code,
%(select_period_query)s
FROM %(table_references)s
JOIN account_journal journal ON journal.id = account_move_line.journal_id
JOIN period_table ON
(
period_table.date_start IS NULL
OR COALESCE(account_move_line.%(aging_date_field)s, account_move_line.date) <= DATE(period_table.date_start)
)
AND
(
period_table.date_stop IS NULL
OR COALESCE(account_move_line.%(aging_date_field)s, account_move_line.date) >= DATE(period_table.date_stop)
)
WHERE %(search_condition)s
GROUP BY %(groupby_clause)s
HAVING
ROUND(SUM(%(residual_at_date)s), %(currency_precision)s) != 0
ORDER BY %(groupby_clause)s
""",
account_code=account_code,
period_table=period_table,
select_from_groupby=select_from_groupby,
residual_at_date=query.table.residual_at_date,
residual_currency_at_date=query.table.residual_currency_at_date,
select_period_query=select_period_query,
multiplicator=multiplicator,
aging_date_field=aging_date_field,
table_references=query.from_clause,
search_condition=query.where_clause,
groupby_clause=groupby_clause,
currency_precision=self.env.company.currency_id.decimal_places,
)
query_res_lines = self.env.execute_query_dict(query)
if not current_groupby:
return {next(iter(formulas_dict.values())): build_result_dict(report, query_res_lines)}
else:
rslt = []
all_res_per_grouping_key = {}
for query_res in query_res_lines:
grouping_key = query_res['grouping_key']
all_res_per_grouping_key.setdefault(grouping_key, []).append(query_res)
for grouping_key, query_res_lines in all_res_per_grouping_key.items():
rslt.append((grouping_key, build_result_dict(report, query_res_lines)))
return {next(iter(formulas_dict.values())): rslt}
def open_journal_items(self, options, params):
params['view_ref'] = 'account.view_move_line_tree_grouped_partner'
options_for_audit = {**options, 'date': {**options['date'], 'date_from': None}}
report = self.env['account.report'].browse(options['report_id'])
action = report.open_journal_items(options=options_for_audit, params=params)
action.get('context', {}).update({'search_default_group_by_account': 0, 'search_default_group_by_partner': 1})
return action
def _common_custom_unfold_all_batch_data_generator(self, internal_type, report, options, lines_to_expand_by_function):
rslt = {} # In the form {full_sub_groupby_key: all_column_group_expression_totals for this groupby computation}
report_periods = 6 # The report has 6 periods
for expand_function_name, lines_to_expand in lines_to_expand_by_function.items():
for line_to_expand in lines_to_expand: # In standard, this loop will execute only once
if expand_function_name == '_report_expand_unfoldable_line_with_groupby':
report_line_id = report._get_res_id_from_line_id(line_to_expand.id, 'account.report.line')
expressions_to_evaluate = report.line_ids.expression_ids.filtered(lambda x: x.report_line_id.id == report_line_id and x.engine == 'custom')
if not expressions_to_evaluate:
continue
formulas_dict = {expressions_to_evaluate[0].formula: expressions_to_evaluate} # We assume they all share the same custom engine
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
# Get all aml results by partner
aml_data_by_partner = {}
for formula_result in self._aged_partner_report_custom_engine_common(column_group_options, internal_type, 'id', formulas_dict).values():
for aml_id, aml_result in formula_result:
aml_result['aml_id'] = aml_id
aml_data_by_partner.setdefault(aml_result['partner_id'], []).append(aml_result)
# Iterate on results by partner to generate the content of the column group
partner_expression_totals = rslt.setdefault(f"[{report_line_id}]=>partner_id", {})\
.setdefault(column_group_index, {expression: {'value': [], 'sublines_info': set()} for expression in expressions_to_evaluate})
for partner_id, aml_data_list in aml_data_by_partner.items():
partner_values = self._prepare_partner_values()
for i in range(report_periods):
partner_values[f'period{i}'] = 0
# Build expression totals under the right key
partner_aml_expression_totals = rslt.setdefault(f"[{report_line_id}]partner_id:{partner_id}=>id", {})\
.setdefault(column_group_index, {expression: {'value': [], 'sublines_info': set()} for expression in expressions_to_evaluate})
for aml_data in aml_data_list:
for i in range(report_periods):
period_value = aml_data[f'period{i}']
partner_values[f'period{i}'] += period_value
partner_values['total'] += period_value
for expression in expressions_to_evaluate:
partner_aml_expression_totals[expression]['value'].append(
(aml_data['aml_id'], aml_data[expression.subformula])
)
for expression in expressions_to_evaluate:
partner_expression_totals[expression]['value'].append(
(partner_id, partner_values[expression.subformula])
)
partner_expression_totals[expression]['sublines_info'].add(partner_id)
return rslt
def _prepare_partner_values(self):
return {
'invoice_date': None,
'due_date': None,
'amount_currency': None,
'currency_id': None,
'currency': None,
'account_name': None,
'total': 0,
}
def aged_partner_balance_audit(self, options, params, journal_type):
""" Open a list of invoices/bills and/or deferral entries for the clicked cell
:param dict options: the report's `options`
:param dict params: a dict containing:
* ``calling_line_dict_id``: line id containing the optional account of the cell
* ``expression_label``: the expression label of the cell
"""
report = self.env['account.report'].browse(options['report_id'])
action = self.env['ir.actions.actions']._for_xml_id('account.action_amounts_to_settle')
journal_type_to_exclude = {'purchase': 'sale', 'sale': 'purchase'}
if options:
domain = [
('account_id.reconcile', '=', True),
('residual_at_date', '!=', 0),
('journal_id.type', '!=', journal_type_to_exclude.get(journal_type)),
*self._build_domain_from_period(options, params['expression_label']),
*report._get_options_domain(options, 'from_beginning'),
*report._get_audit_line_groupby_domain(params['calling_line_dict_id']),
]
action['domain'] = domain
action['context'] = {
'recon_limit': options['date']['date_to'],
}
if recon_date := report._get_option_recon_date(options):
action['context']['search_default_open_on'] = recon_date.strftime('%Y-%m-%d')
return action
def _build_domain_from_period(self, options, period):
if period != "total" and period[-1].isdigit():
period_number = int(period[-1])
if period_number == 0:
domain = [
'|',
('date_maturity', '>=', options['date']['date_to']),
'&', ('date_maturity', '=', False), ('date', '>=', options['date']['date_to']),
]
else:
options_date_to = datetime.datetime.strptime(options['date']['date_to'], '%Y-%m-%d')
period_end = options_date_to - datetime.timedelta(30*(period_number-1)+1)
period_start = options_date_to - datetime.timedelta(30*(period_number))
domain = [
'|',
'&', ('date_maturity', '>=', period_start), ('date_maturity', '<=', period_end),
'&', '&', ('date_maturity', '=', False), ('date', '>=', period_start), ('date', '<=', period_end),
]
if period_number == 5:
domain = [
'|',
('date_maturity', '<=', period_end),
'&', ('date_maturity', '=', False), ('date', '<=', period_end),
]
else:
domain = []
return domain
def open_followup_report(self, options, params):
partner_id = self.env['account.report']._get_res_id_from_line_id(params['line_id'], 'res.partner')
followup_report = self.env.ref('account_reports.followup_report')
followup_options = followup_report.get_options(options)
followup_options['unfold_all'] = True
if partner_id:
followup_options['partner_ids'] = [partner_id]
action_vals = self.env['ir.actions.actions']._for_xml_id('account_reports.action_account_report_followup')
action_vals['params'] = {
'options': followup_options,
'ignore_session': True,
}
return action_vals
class AccountAgedPayableReportHandler(models.AbstractModel):
_name = 'account.aged.payable.report.handler'
_inherit = ['account.aged.partner.balance.report.handler']
_description = 'Aged Payable Custom Handler'
def open_journal_items(self, options, params):
payable_account_type = {'id': 'trade_payable', 'name': _("Payable"), 'selected': True}
if 'account_type' in options:
options['account_type'].append(payable_account_type)
else:
options['account_type'] = [payable_account_type]
return super().open_journal_items(options, params)
def _custom_unfold_all_batch_data_generator(self, report, options, lines_to_expand_by_function):
# We only optimize the unfold all if the groupby value of the report has not been customized. Else, we'll just run the full computation
aged_payable_line = self.env.ref('account_reports.aged_payable_line')
if aged_payable_line._get_groupby(options).replace(' ', '') == (aged_payable_line.groupby or report.groupby).replace(' ', ''):
return self._common_custom_unfold_all_batch_data_generator('liability_payable', report, options, lines_to_expand_by_function)
return {}
def action_audit_cell(self, options, params):
return self.aged_partner_balance_audit(options, params, 'purchase')
class AccountAgedReceivableReportHandler(models.AbstractModel):
_name = 'account.aged.receivable.report.handler'
_inherit = ['account.aged.partner.balance.report.handler']
_description = 'Aged Receivable Custom Handler'
def open_journal_items(self, options, params):
receivable_account_type = {'id': 'trade_receivable', 'name': _("Receivable"), 'selected': True}
if 'account_type' in options:
options['account_type'].append(receivable_account_type)
else:
options['account_type'] = [receivable_account_type]
return super().open_journal_items(options, params)
def _custom_unfold_all_batch_data_generator(self, report, options, lines_to_expand_by_function):
# We only optimize the unfold all if the groupby value of the report has not been customized. Else, we'll just run the full computation
aged_receivable_line = self.env.ref('account_reports.aged_receivable_line')
if aged_receivable_line._get_groupby(options).replace(' ', '') == (aged_receivable_line.groupby or report.groupby).replace(' ', ''):
return self._common_custom_unfold_all_batch_data_generator('asset_receivable', report, options, lines_to_expand_by_function)
return {}
def action_audit_cell(self, options, params):
return self.aged_partner_balance_audit(options, params, 'sale')

View File

@@ -0,0 +1,41 @@
from odoo import api, fields, models
from odoo.tools import SQL
class AccountAnalyticLine(models.Model):
_inherit = 'account.analytic.line'
analytic_coverage = fields.Float(
string="Analytic Coverage",
compute='_compute_analytic_coverage',
compute_sql='_compute_sql_analytic_coverage',
compute_sudo=True,
)
def _compute_sql_analytic_coverage(self, table) -> SQL:
plan_id = self.env.context.get('selected_analytic_plan')
if not plan_id:
return SQL("0.0")
column_name = self.env['account.analytic.plan'].browse(plan_id)._column_name()
amount_sql = SQL(
"CASE WHEN %s = %s THEN %s ELSE 0 END",
table[column_name].plan_id,
plan_id,
table.amount,
)
return SQL(
"COALESCE(-(%(amount)s / NULLIF(%(balance)s, 0)), 0)",
amount=amount_sql,
balance=table.move_line_id.balance,
)
@api.depends('amount', 'move_line_id.balance', 'auto_account_id')
def _compute_analytic_coverage(self):
query = self._search([('id', 'in', self.ids)])
line2coverage = dict(self.env.execute_query(query.select(
query.table.id,
query.table.analytic_coverage,
)))
for line in self:
line.analytic_coverage = line2coverage[line._origin.id]

View File

@@ -0,0 +1,257 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import ast
from odoo import _, models, fields, api
from odoo.fields import Domain
from odoo.addons.web.controllers.utils import clean_action
from odoo.models import Query
from odoo.tools import SQL
class AccountReport(models.Model):
_inherit = 'account.report'
filter_analytic_groupby = fields.Boolean(
string="Analytic Group By",
compute=lambda x: x._compute_report_option_filter('filter_analytic_groupby'), readonly=False, store=True, depends=['root_report_id', 'section_main_report_ids'],
)
def _get_options_initializers_forced_sequence_map(self):
""" Force the sequence for the init_options so columns headers are already generated but not the columns
So, between _init_options_column_headers and _init_options_columns"""
sequence_map = super(AccountReport, self)._get_options_initializers_forced_sequence_map()
sequence_map[self._init_options_analytic_groupby] = 995
return sequence_map
def _init_options_analytic_groupby(self, options, previous_options):
if not self.filter_analytic_groupby:
return
enable_analytic_accounts = self.env.user.has_group('analytic.group_analytic_accounting')
if not enable_analytic_accounts:
return
options['display_analytic_groupby'] = True
options['display_analytic_plan_groupby'] = True
options['include_analytic_without_aml'] = previous_options.get('include_analytic_without_aml', False)
previous_analytic_accounts = previous_options.get('analytic_accounts_groupby', [])
analytic_account_ids = [int(x) for x in previous_analytic_accounts]
selected_analytic_accounts = self.env['account.analytic.account'].with_context(active_test=False).search(
[('id', 'in', analytic_account_ids)])
options['analytic_accounts_groupby'] = selected_analytic_accounts.ids
options['selected_analytic_account_groupby_names'] = selected_analytic_accounts.mapped('name')
previous_analytic_plans = previous_options.get('analytic_plans_groupby', [])
analytic_plan_ids = [int(x) for x in previous_analytic_plans]
selected_analytic_plans = self.env['account.analytic.plan'].search([('id', 'in', analytic_plan_ids)])
options['analytic_plans_groupby'] = selected_analytic_plans.ids
options['selected_analytic_plan_groupby_names'] = selected_analytic_plans.mapped('name')
self._create_column_analytic(options)
def _create_column_analytic(self, options):
""" Creates the analytic columns for each plan or account in the filters.
This will duplicate all previous columns and adding the analytic accounts in the domain of the added columns.
The analytic_groupby_option is used so the table used is the shadowed table.
The domain on analytic_distribution can just use simple comparison as the column of the shadowed
table will simply be filled with analytic_account_ids.
"""
analytic_headers = []
plans = self.env['account.analytic.plan'].browse(options.get('analytic_plans_groupby'))
for plan in plans:
account_list = []
accounts = self.env['account.analytic.account'].search([('plan_id', 'child_of', plan.id)])
for account in accounts:
account_list.append(account.id)
analytic_headers.append({
'name': plan.name,
'forced_options': {
'analytic_groupby_option': True,
'analytic_accounts_list': tuple(account_list), # Analytic accounts used in the domain to filter the lines.
'analytic_plan_id': plan.id,
}
})
accounts = self.env['account.analytic.account'].browse(options.get('analytic_accounts_groupby'))
for account in accounts:
analytic_headers.append({
'name': account.name,
'forced_options': {
'analytic_groupby_option': True,
'analytic_accounts_list': (account.id,),
}
})
if analytic_headers:
has_selected_budgets = any([budget for budget in options.get('budgets', []) if budget['selected']])
if has_selected_budgets and not options['selected_horizontal_group_id']:
# if budget is selected, then analytic headers are placed on the same header level
options['column_headers'][-1] = analytic_headers + options['column_headers'][-1]
else:
# We add the analytic layer to the column_headers before creating the columns
analytic_headers.append({'name': _("Total")})
options['column_headers'] = [
*options['column_headers'],
analytic_headers,
]
@api.model
def _create_aml_shadowing_query_for_analytic_groupby(self):
"""Prepares a SQL query to shadow the account_move_line table with
the data from account_analytic_line in reports.
It will return a new table with the schema of account_move_line table, but with
the data from account_analytic_line.
We inherit the schema of account_move_line, make the correspondence between
account_move_line fields and account_analytic_line fields and put NULL for those
who don't exist in account_analytic_line.
We also drop the NOT NULL constraints for fields who are not required in account_analytic_line.
"""
project_plan, other_plans = self.env['account.analytic.plan']._get_all_plans()
analytic_cols = SQL(", ").join(SQL('"account_analytic_line".%s', SQL.identifier(n._column_name())) for n in (project_plan + other_plans))
analytic_distribution_equivalent = SQL('to_jsonb(UNNEST(ARRAY_REMOVE(ARRAY[%s], NULL)))', analytic_cols)
change_equivalence_dict = {
'balance': SQL("-amount"),
'display_type': 'product',
'parent_state': 'posted',
'account_id': SQL.identifier("general_account_id"),
'debit': SQL("CASE WHEN (amount < 0) THEN -amount else 0 END"),
'credit': SQL("CASE WHEN (amount > 0) THEN amount else 0 END"),
'analytic_distribution': analytic_distribution_equivalent,
'date': SQL("account_analytic_line.date"),
'company_id': SQL("account_analytic_line.company_id"),
}
all_stored_aml_fields = {
field
for field, attrs in self.env['account.move.line'].fields_get(attributes=["type", "store"]).items()
if attrs['type'] not in ['many2many', 'one2many'] and attrs.get('store')
}
for aml_field in all_stored_aml_fields:
if aml_field not in change_equivalence_dict:
change_equivalence_dict[aml_field] = SQL('"account_move_line".%s', SQL.identifier(aml_field))
_stored_fields, fields_to_insert = self.env['account.move.line']._prepare_aml_shadowing_for_report(change_equivalence_dict)
return SQL("""
(
SELECT %(fields_to_insert)s
FROM account_analytic_line
LEFT JOIN account_move_line
ON account_analytic_line.move_line_id = account_move_line.id
WHERE
account_analytic_line.general_account_id IS NOT NULL
)
""", fields_to_insert=fields_to_insert)
def _get_report_query(self, options, date_scope, domain=None, cta_date_to=None) -> Query:
# Override to add the context key which will eventually trigger the shadowing of the table
context_self = self.with_context(account_report_analytic_groupby=options.get('analytic_groupby_option'))
return super(AccountReport, context_self)._get_report_query(options, date_scope, domain, cta_date_to=cta_date_to)
def action_audit_cell(self, options, params):
column_group_options = self._get_column_group_options(options, params['column_group_index'])
if not column_group_options.get('analytic_groupby_option'):
action = super().action_audit_cell(options, params)
if options.get('column_percent_comparison') == 'analytic_coverage':
context = action.get('context', {})
context.update({
'selected_analytic_plan': options['analytic_plans_groupby'][0],
})
action['context'] = context
view_id = self.env.ref('account_reports.view_analytic_move_line_tree', raise_if_not_found=False) or False
if view_id:
action['views'] = [(view_id.id, 'list')]
return action
else:
# Start by getting the domain from the options. Note that this domain is targeting account.move.line
report_line = self.env['account.report.line'].browse(params['report_line_id'])
expression = report_line.expression_ids.filtered(lambda x: x.label == params['expression_label'])
line_domain = self._get_audit_line_domain(column_group_options, expression, params)
# The line domain is made for move lines, so we need some postprocessing to have it work with analytic lines.
domain = []
AccountAnalyticLine = self.env['account.analytic.line']
for expression in line_domain:
if len(expression) == 1: # For operators such as '&' or '|' we can juste add them again.
domain.append(expression)
continue
field, operator, right_term = expression
# On analytic lines, the account.account field is named general_account_id and not account_id.
if field.split('.')[0] == 'account_id':
field = field.replace('account_id', 'general_account_id')
expression = [(field, operator, right_term)]
elif field == 'analytic_distribution':
if options.get('column_percent_comparison') == 'analytic_coverage':
expression = [(1, '=', 1)]
else:
expression = [('auto_account_id', 'in', right_term)]
# For other fields not present in on the analytic line model, map them to get the info from the move_line.
# Or ignore these conditions if there is no move lines.
elif field.split('.')[0] not in AccountAnalyticLine._fields:
expression = [(f'move_line_id.{field}', operator, right_term)]
if options.get('include_analytic_without_aml'):
expression = Domain.OR([
[('move_line_id', '=', False)],
expression,
])
else:
expression = [expression] # just for the extend
domain.extend(expression)
action = clean_action(self.env.ref('analytic.account_analytic_line_action_entries')._get_action_dict(), env=self.env)
action['domain'] = domain
action['context'] = ast.literal_eval(action.get('context', "{}"))
if options.get('column_percent_comparison') == 'analytic_coverage':
action['context'].update({
'selected_analytic_plan': options['analytic_plans_groupby'][0],
'group_by': 'move_line_id',
})
action['display_name'] += ' - ' + options['selected_analytic_plan_groupby_names'][0]
view_id = self.env.ref('account_reports.view_analytic_line_tree', raise_if_not_found=False) or False
if view_id:
action['views'] = [(view_id.id, 'list')]
return action
@api.model
def _get_options_journals_domain(self, options):
domain = super()._get_options_journals_domain(options)
# Add False to the domain in order to select lines without journals for analytics columns.
if options.get('include_analytic_without_aml'):
domain |= Domain('journal_id', '=', False)
return domain
def _get_options_domain(self, options, date_scope):
self.ensure_one()
domain = super()._get_options_domain(options, date_scope)
# Get the analytic accounts that we need to filter on from the options and add a domain for them.
if 'analytic_accounts_list' in options:
domain &= Domain('analytic_distribution', 'in', options.get('analytic_accounts_list', []))
return domain
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
@api.model
def _search(self, *args, **kwargs):
""" In case we need an analytic column in an account_report, we shadow the account_move_line table
with a temp table filled with analytic data, that will be used for the analytic columns.
We do it in this function to only create and fill it once for all computations of a report.
The following analytic columns and computations will just query the shadowed table instead of the real one.
"""
query = super()._search(*args, **kwargs)
if self.env.context.get('account_report_analytic_groupby') and not self.env.context.get('account_report_cash_basis'):
join, sql, condition = query._joins['account_move_line']
sql = self.env['account.report']._create_aml_shadowing_query_for_analytic_groupby()
query._joins['account_move_line'] = join, sql, condition
return query

View File

@@ -0,0 +1,13 @@
from odoo import fields, models
from odoo.addons.account.models.account_move import REVIEW_STATE_SELECTION
class AccountAuditAccountStatus(models.Model):
_name = "account.audit.account.status"
_description = "Account Audit Account Status"
audit_id = fields.Many2one(string="Audit", comodel_name='account.return', required=True, ondelete='cascade', index="btree")
account_id = fields.Many2one(string="Account", comodel_name='account.account', required=True, ondelete='cascade', index="btree")
status = fields.Selection(
selection=REVIEW_STATE_SELECTION,
)

View File

@@ -0,0 +1,697 @@
from odoo import _, fields, models
from odoo.models import Query
from odoo.tools import SQL
from odoo.addons.account_reports.utils.report_data_objects import AccountReportLineData
class AccountCashFlowReportHandler(models.AbstractModel):
_name = 'account.cash.flow.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Cash Flow Report Custom Handler'
def _dynamic_lines_generator(self, report, options, all_column_groups_expression_totals, warnings=None):
# Compute the cash flow report using the direct method: https://www.investopedia.com/terms/d/direct_method.asp
lines = []
layout_data = self._get_layout_data()
report_data = self._get_report_data(report, options, layout_data)
for layout_line_id, layout_line_data in layout_data.items():
lines.append((0, self._get_layout_line(report, options, layout_line_id, layout_line_data, report_data)))
if layout_line_id in report_data and 'aml_groupby_account' in report_data[layout_line_id]:
aml_data_values = report_data[layout_line_id]['aml_groupby_account'].values()
aml_data_values_with_account_code = []
aml_data_values_without_account_code = []
for aml_data in aml_data_values:
if aml_data['account_code'] is not None:
aml_data_values_with_account_code.append(aml_data)
else:
aml_data_values_without_account_code.append(aml_data)
for aml_data in (sorted(aml_data_values_with_account_code, key=lambda x: x['account_code'])
+ aml_data_values_without_account_code):
lines.append((0, self._get_aml_line(report, options, aml_data)))
unexplained_difference_line = self._get_unexplained_difference_line(report, options, report_data)
if unexplained_difference_line:
lines.append((0, unexplained_difference_line))
return lines
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
report._init_options_journals(options, previous_options=previous_options, additional_journals_domain=[('type', 'in', ('bank', 'cash', 'general'))])
report._init_options_journals_names(options, previous_options=previous_options, additional_journals_domain=[('type', 'in', ('bank', 'cash', 'general'))])
def _get_report_data(self, report, options, layout_data):
report_data = {}
payment_account_ids = self._get_account_ids(report, options)
if not payment_account_ids:
return report_data
# Compute 'Cash and cash equivalents, beginning of period'
for aml_data in self._compute_liquidity_balance(report, options, payment_account_ids, 'to_beginning_of_period'):
self._add_report_data('opening_balance', aml_data, layout_data, report_data)
self._add_report_data('closing_balance', aml_data, layout_data, report_data)
# Compute 'Cash and cash equivalents, closing balance'
for aml_data in self._compute_liquidity_balance(report, options, payment_account_ids, 'strict_range'):
self._add_report_data('closing_balance', aml_data, layout_data, report_data)
tags_ids = self._get_tags_ids()
cashflow_tag_ids = self._get_cashflow_tag_ids()
# Process liquidity moves
for aml_groupby_account in self._get_liquidity_moves(report, options, payment_account_ids, cashflow_tag_ids):
for aml_data in aml_groupby_account.values():
self._dispatch_aml_data(tags_ids, aml_data, layout_data, report_data)
# Process reconciled moves
for aml_groupby_account in self._get_reconciled_moves(report, options, payment_account_ids, cashflow_tag_ids):
for aml_data in aml_groupby_account.values():
self._dispatch_aml_data(tags_ids, aml_data, layout_data, report_data)
return report_data
def _add_report_data(self, layout_line_id, aml_data, layout_data, report_data):
"""
Add or update the report_data dictionnary with aml_data.
report_data is a dictionnary where the keys are keys from _cash_flow_report_get_layout_data() (used for mapping)
and the values can contain 2 dictionnaries:
* (required) 'balance' where the key is the column_group_index and the value is the balance of the line
* (optional) 'aml_groupby_account' where the key is an account_id and the values are the aml data
"""
def _report_update_parent(layout_line_id, aml_column_group_index, aml_balance, layout_data, report_data):
# Update the balance in report_data of the parent of the layout_line_id recursively (Stops when the line has no parent)
if 'parent_line_id' in layout_data[layout_line_id]:
parent_line_id = layout_data[layout_line_id]['parent_line_id']
report_data.setdefault(parent_line_id, {'balance': {}})
report_data[parent_line_id]['balance'].setdefault(aml_column_group_index, 0.0)
report_data[parent_line_id]['balance'][aml_column_group_index] += aml_balance
_report_update_parent(parent_line_id, aml_column_group_index, aml_balance, layout_data, report_data)
aml_column_group_index = aml_data['column_group_index']
aml_account_id = aml_data['account_id']
aml_account_code = aml_data['account_code']
aml_account_name = aml_data['account_name']
aml_balance = aml_data['balance']
aml_account_tag = aml_data.get('account_tag_id', None)
if self.env.company.currency_id.is_zero(aml_balance):
return
report_data.setdefault(layout_line_id, {
'balance': {},
'aml_groupby_account': {},
})
report_data[layout_line_id]['aml_groupby_account'].setdefault(aml_account_id, {
'parent_line_id': layout_line_id,
'account_id': aml_account_id,
'account_code': aml_account_code,
'account_name': aml_account_name,
'account_tag_id': aml_account_tag,
'level': layout_data[layout_line_id]['level'] + 1,
'balance': {},
})
report_data[layout_line_id]['balance'].setdefault(aml_column_group_index, 0.0)
report_data[layout_line_id]['balance'][aml_column_group_index] += aml_balance
report_data[layout_line_id]['aml_groupby_account'][aml_account_id]['balance'].setdefault(aml_column_group_index, 0.0)
report_data[layout_line_id]['aml_groupby_account'][aml_account_id]['balance'][aml_column_group_index] += aml_balance
_report_update_parent(layout_line_id, aml_column_group_index, aml_balance, layout_data, report_data)
def _get_tags_ids(self):
''' Get a dict to pass on to _dispatch_aml_data containing information mapping account tags to report lines. '''
return {
'operating': self.env.ref('account.account_tag_operating').id,
'investing': self.env.ref('account.account_tag_investing').id,
'financing': self.env.ref('account.account_tag_financing').id,
}
def _get_cashflow_tag_ids(self):
''' Get the list of account tags that are relevant for the cash flow report. '''
return self._get_tags_ids().values()
def _dispatch_aml_data(self, tags_ids, aml_data, layout_data, report_data):
# Dispatch the aml_data in the correct layout_line
if aml_data['account_account_type'] == 'asset_receivable':
self._add_report_data('advance_payments_customer', aml_data, layout_data, report_data)
elif aml_data['account_account_type'] == 'liability_payable':
self._add_report_data('advance_payments_suppliers', aml_data, layout_data, report_data)
elif aml_data['balance'] < 0:
if aml_data['account_tag_id'] == tags_ids['operating']:
self._add_report_data('paid_operating_activities', aml_data, layout_data, report_data)
elif aml_data['account_tag_id'] == tags_ids['investing']:
self._add_report_data('investing_activities_cash_out', aml_data, layout_data, report_data)
elif aml_data['account_tag_id'] == tags_ids['financing']:
self._add_report_data('financing_activities_cash_out', aml_data, layout_data, report_data)
else:
self._add_report_data('unclassified_activities_cash_out', aml_data, layout_data, report_data)
elif aml_data['balance'] > 0:
if aml_data['account_tag_id'] == tags_ids['operating']:
self._add_report_data('received_operating_activities', aml_data, layout_data, report_data)
elif aml_data['account_tag_id'] == tags_ids['investing']:
self._add_report_data('investing_activities_cash_in', aml_data, layout_data, report_data)
elif aml_data['account_tag_id'] == tags_ids['financing']:
self._add_report_data('financing_activities_cash_in', aml_data, layout_data, report_data)
else:
self._add_report_data('unclassified_activities_cash_in', aml_data, layout_data, report_data)
# -------------------------------------------------------------------------
# QUERIES
# -------------------------------------------------------------------------
def _get_account_ids(self, report, options):
''' Retrieve all accounts to be part of the cash flow statement and also the accounts making them.
:param options: The report options.
:return: payment_account_ids: A tuple containing all account.account's ids being used in a liquidity journal.
'''
# Fetch liquidity accounts:
# Accounts being used by at least one bank/cash journal.
selected_journal_ids = [j['id'] for j in report._get_options_journals(options)]
where_clause = "account_journal.id IN %s" if selected_journal_ids else "account_journal.type IN ('bank', 'cash', 'general')"
where_params = [tuple(selected_journal_ids)] if selected_journal_ids else []
self.env.cr.execute(f'''
SELECT
array_remove(ARRAY_AGG(DISTINCT account_account.id), NULL),
array_remove(ARRAY_AGG(DISTINCT account_payment_method_line.payment_account_id), NULL)
FROM account_journal
JOIN res_company
ON account_journal.company_id = res_company.id
LEFT JOIN account_payment_method_line
ON account_journal.id = account_payment_method_line.journal_id
LEFT JOIN account_account
ON account_journal.default_account_id = account_account.id
AND account_account.account_type IN ('asset_cash', 'liability_credit_card')
WHERE {where_clause}
''', where_params)
res = self.env.cr.fetchall()[0]
payment_account_ids = set((res[0] or []) + (res[1] or []))
if not payment_account_ids:
return ()
return tuple(payment_account_ids)
def _get_move_ids_query(self, report, payment_account_ids, column_group_options) -> SQL:
''' Get all liquidity moves to be part of the cash flow statement.
:param payment_account_ids: A tuple containing all account.account's ids being used in a liquidity journal.
:return: query: The SQL query to retrieve the move IDs.
'''
query = report._get_report_query(column_group_options, 'strict_range', [('account_id', 'in', list(payment_account_ids))])
return SQL(
'''
SELECT
array_agg(DISTINCT account_move_line.move_id) AS move_id
FROM %(table_references)s
WHERE %(search_condition)s
''',
table_references=query.from_clause,
search_condition=query.where_clause,
)
def _compute_liquidity_balance(self, report, options, payment_account_ids, date_scope):
''' Compute the balance of all liquidity accounts to populate the following sections:
'Cash and cash equivalents, beginning of period' and 'Cash and cash equivalents, closing balance'.
:param options: The report options.
:param payment_account_ids: A tuple containing all account.account's ids being used in a liquidity journal.
:return: A list of tuple (account_id, account_code, account_name, balance).
'''
queries = []
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
query = report._get_report_query(column_group_options, date_scope, domain=[('account_id', 'in', payment_account_ids)])
account_t = query.table._sudo()._join('account_id', kind='JOIN')
queries.append(SQL(
'''
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.account_id,
%(account_code)s AS account_code,
%(account_name)s AS account_name,
SUM(%(balance_select)s) AS balance
FROM %(table_references)s
WHERE %(search_condition)s
GROUP BY account_move_line.account_id, %(account_code)s, %(account_name)s
''',
column_group_index=column_group_index,
account_code=account_t.code,
account_name=account_t.name,
balance_select=query.table.consolidation_balance,
table_references=query.from_clause,
search_condition=query.where_clause,
))
self.env.cr.execute(SQL(' UNION ALL ').join(queries))
return self.env.cr.dictfetchall()
def _get_liquidity_moves(self, report, options, payment_account_ids, cash_flow_tag_ids):
''' Fetch all information needed to compute lines from liquidity moves.
The difficulty is to represent only the not-reconciled part of balance.
:param options: The report options.
:param payment_account_ids: A tuple containing all account.account's ids being used in a liquidity journal.
:return: A list of tuple (account_id, account_code, account_name, account_type, amount).
'''
reconciled_aml_groupby_account = {}
queries = []
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
move_ids_query = self._get_move_ids_query(report, payment_account_ids, column_group_options)
query = Query(self.env['account.move.line'].with_context(date_to=column_group_options['date']['date_to']))
account_t = query.table._sudo()._join('account_id', kind='JOIN')
queries.append(SQL(
'''
(WITH payment_move_ids AS (%(move_ids_query)s)
-- Credit amount of each account
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.account_id,
%(account_code)s AS account_code,
%(account_name)s AS account_name,
%(account_type)s AS account_account_type,
account_account_account_tag.account_account_tag_id AS account_tag_id,
SUM(%(partial_amount_select)s) AS balance
FROM %(from_clause)s
LEFT JOIN account_partial_reconcile
ON account_partial_reconcile.credit_move_id = account_move_line.id
LEFT JOIN account_account_account_tag
ON account_account_account_tag.account_account_id = account_move_line.account_id
AND account_account_account_tag.account_account_tag_id IN %(cash_flow_tag_ids)s
WHERE account_move_line.move_id IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND account_move_line.account_id NOT IN %(payment_account_ids)s
AND account_partial_reconcile.max_date BETWEEN %(date_from)s AND %(date_to)s
GROUP BY account_move_line.company_id, account_move_line.account_id, %(account_code)s, %(account_name)s, account_account_type, account_account_account_tag.account_account_tag_id
UNION ALL
-- Debit amount of each account
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.account_id,
%(account_code)s AS account_code,
%(account_name)s AS account_name,
%(account_type)s AS account_account_type,
account_account_account_tag.account_account_tag_id AS account_tag_id,
-SUM(%(partial_amount_select)s) AS balance
FROM %(from_clause)s
LEFT JOIN account_partial_reconcile
ON account_partial_reconcile.debit_move_id = account_move_line.id
LEFT JOIN account_account_account_tag
ON account_account_account_tag.account_account_id = account_move_line.account_id
AND account_account_account_tag.account_account_tag_id IN %(cash_flow_tag_ids)s
WHERE account_move_line.move_id IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND account_move_line.account_id NOT IN %(payment_account_ids)s
AND account_partial_reconcile.max_date BETWEEN %(date_from)s AND %(date_to)s
GROUP BY account_move_line.company_id, account_move_line.account_id, %(account_code)s, %(account_name)s, account_account_type, account_account_account_tag.account_account_tag_id
UNION ALL
-- Total amount of each account
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.account_id AS account_id,
%(account_code)s AS account_code,
%(account_name)s AS account_name,
%(account_type)s AS account_account_type,
account_account_account_tag.account_account_tag_id AS account_tag_id,
SUM(%(aml_balance_select)s) AS balance
FROM %(from_clause)s
LEFT JOIN account_account_account_tag
ON account_account_account_tag.account_account_id = account_move_line.account_id
AND account_account_account_tag.account_account_tag_id IN %(cash_flow_tag_ids)s
WHERE account_move_line.move_id IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND account_move_line.account_id NOT IN %(payment_account_ids)s
GROUP BY account_move_line.account_id, %(account_code)s, %(account_name)s, account_account_type, account_account_account_tag.account_account_tag_id)
''',
column_group_index=column_group_index,
move_ids_query=move_ids_query,
account_code=account_t.code,
account_name=account_t.name,
account_type=account_t.account_type,
partial_amount_select=SQL("account_partial_reconcile.amount * %s", query.table.consolidation_rate),
aml_balance_select=query.table.consolidation_balance,
from_clause=query.from_clause,
cash_flow_tag_ids=tuple(cash_flow_tag_ids),
payment_account_ids=payment_account_ids,
date_from=column_group_options['date']['date_from'],
date_to=column_group_options['date']['date_to'],
))
self.env.cr.execute(SQL(' UNION ALL ').join(queries))
for aml_data in self.env.cr.dictfetchall():
reconciled_aml_groupby_account.setdefault(aml_data['account_id'], {})
reconciled_aml_groupby_account[aml_data['account_id']].setdefault(aml_data['column_group_index'], {
'column_group_index': aml_data['column_group_index'],
'account_id': aml_data['account_id'],
'account_code': aml_data['account_code'],
'account_name': aml_data['account_name'],
'account_account_type': aml_data['account_account_type'],
'account_tag_id': aml_data['account_tag_id'],
'balance': 0.0,
})
reconciled_aml_groupby_account[aml_data['account_id']][aml_data['column_group_index']]['balance'] -= aml_data['balance']
return list(reconciled_aml_groupby_account.values())
def _get_reconciled_moves(self, report, options, payment_account_ids, cash_flow_tag_ids):
''' Retrieve all moves being not a liquidity move to be shown in the cash flow statement.
Each amount must be valued at the percentage of what is actually paid.
E.g. An invoice of 1000 being paid at 50% must be valued at 500.
:param options: The report options.
:param payment_account_ids: A tuple containing all account.account's ids being used in a liquidity journal.
:return: A list of tuple (account_id, account_code, account_name, account_type, amount).
'''
reconciled_account_ids = {column_group_index: set() for column_group_index in range(len(options['column_groups']))}
reconciled_percentage_per_move = {column_group_index: {} for column_group_index in range(len(options['column_groups']))}
queries = []
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
move_ids_query = self._get_move_ids_query(report, payment_account_ids, column_group_options)
AccountMoveLine = self.env['account.move.line'].with_context(date_to=column_group_options['date']['date_to'])
credit_query = Query(AccountMoveLine, 'credit_line')
debit_query = Query(AccountMoveLine, 'debit_line')
queries.append(SQL(
'''
(WITH payment_move_ids AS (%(move_ids_query)s)
SELECT
%(column_group_index)s AS column_group_index,
debit_line.move_id,
debit_line.account_id,
SUM(%(partial_amount_credit)s) AS balance
FROM %(from_credit)s
LEFT JOIN account_partial_reconcile
ON account_partial_reconcile.credit_move_id = credit_line.id
INNER JOIN account_move_line AS debit_line
ON debit_line.id = account_partial_reconcile.debit_move_id
WHERE credit_line.move_id IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND credit_line.account_id NOT IN %(payment_account_ids)s
AND credit_line.credit > 0.0
AND debit_line.move_id NOT IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND account_partial_reconcile.max_date BETWEEN %(date_from)s AND %(date_to)s
GROUP BY debit_line.move_id, debit_line.account_id
UNION ALL
SELECT
%(column_group_index)s AS column_group_index,
credit_line.move_id,
credit_line.account_id,
-SUM(%(partial_amount_debit)s) AS balance
FROM %(from_debit)s
LEFT JOIN account_partial_reconcile
ON account_partial_reconcile.debit_move_id = debit_line.id
INNER JOIN account_move_line AS credit_line
ON credit_line.id = account_partial_reconcile.credit_move_id
WHERE debit_line.move_id IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND debit_line.account_id NOT IN %(payment_account_ids)s
AND debit_line.debit > 0.0
AND credit_line.move_id NOT IN (SELECT unnest(payment_move_ids.move_id) FROM payment_move_ids)
AND account_partial_reconcile.max_date BETWEEN %(date_from)s AND %(date_to)s
GROUP BY credit_line.move_id, credit_line.account_id)
''',
move_ids_query=move_ids_query,
column_group_index=column_group_index,
payment_account_ids=payment_account_ids,
date_from=column_group_options['date']['date_from'],
date_to=column_group_options['date']['date_to'],
partial_amount_credit=SQL("account_partial_reconcile.amount * %s", credit_query.table.consolidation_rate),
from_credit=credit_query.from_clause,
partial_amount_debit=SQL("account_partial_reconcile.amount * %s", debit_query.table.consolidation_rate),
from_debit=debit_query.from_clause,
))
self.env.cr.execute(SQL(' UNION ALL ').join(queries))
for aml_data in self.env.cr.dictfetchall():
reconciled_percentage_per_move[aml_data['column_group_index']].setdefault(aml_data['move_id'], {})
reconciled_percentage_per_move[aml_data['column_group_index']][aml_data['move_id']].setdefault(aml_data['account_id'], [0.0, 0.0])
reconciled_percentage_per_move[aml_data['column_group_index']][aml_data['move_id']][aml_data['account_id']][0] += aml_data['balance']
reconciled_account_ids[aml_data['column_group_index']].add(aml_data['account_id'])
if not reconciled_percentage_per_move:
return []
queries = []
today = fields.Date.context_today(self)
for column in options['columns']:
query = Query(self.env['account.move.line'].with_context(date_to=today))
queries.append(SQL(
'''
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.move_id,
account_move_line.account_id,
SUM(%(balance_select)s) AS balance
FROM %(from_clause)s
WHERE account_move_line.move_id IN %(move_ids)s
AND account_move_line.account_id IN %(account_ids)s
GROUP BY account_move_line.move_id, account_move_line.account_id
''',
column_group_index=column['column_group_index'],
balance_select=query.table.consolidation_balance,
from_clause=query.from_clause,
move_ids=tuple(reconciled_percentage_per_move[column['column_group_index']].keys()) or (None,),
account_ids=tuple(reconciled_account_ids[column['column_group_index']]) or (None,)
))
self.env.cr.execute(SQL(' UNION ALL ').join(queries))
for aml_data in self.env.cr.dictfetchall():
if aml_data['account_id'] in reconciled_percentage_per_move[aml_data['column_group_index']][aml_data['move_id']]:
reconciled_percentage_per_move[aml_data['column_group_index']][aml_data['move_id']][aml_data['account_id']][1] += aml_data['balance']
reconciled_aml_per_account = {}
queries = []
query = Query(self.env['account.move.line'].with_context(date_to=today))
account_t = query.table._sudo()._join('account_id', kind='JOIN')
for column in options['columns']:
queries.append(SQL(
'''
SELECT
%(column_group_index)s AS column_group_index,
account_move_line.move_id,
account_move_line.account_id,
%(account_code)s AS account_code,
%(account_name)s AS account_name,
%(account_type)s AS account_account_type,
account_account_account_tag.account_account_tag_id AS account_tag_id,
SUM(%(balance_select)s) AS balance
FROM %(from_clause)s
LEFT JOIN account_account_account_tag
ON account_account_account_tag.account_account_id = account_move_line.account_id
AND account_account_account_tag.account_account_tag_id IN %(cash_flow_tag_ids)s
WHERE account_move_line.move_id IN %(move_ids)s
GROUP BY account_move_line.move_id, account_move_line.account_id, %(account_code)s, %(account_name)s, account_account_type, account_account_account_tag.account_account_tag_id
''',
column_group_index=column['column_group_index'],
account_code=account_t.code,
account_name=account_t.name,
account_type=account_t.account_type,
balance_select=query.table.consolidation_balance,
from_clause=query.from_clause,
cash_flow_tag_ids=tuple(cash_flow_tag_ids),
move_ids=tuple(reconciled_percentage_per_move[column['column_group_index']].keys()) or (None,)
))
self.env.cr.execute(SQL(' UNION ALL ').join(queries))
for aml_data in self.env.cr.dictfetchall():
aml_column_group_index = aml_data['column_group_index']
aml_move_id = aml_data['move_id']
aml_account_id = aml_data['account_id']
aml_account_code = aml_data['account_code']
aml_account_name = aml_data['account_name']
aml_account_account_type = aml_data['account_account_type']
aml_account_tag_id = aml_data['account_tag_id']
aml_balance = aml_data['balance']
# Compute the total reconciled for the whole move.
total_reconciled_amount = 0.0
total_amount = 0.0
for reconciled_amount, amount in reconciled_percentage_per_move[aml_column_group_index][aml_move_id].values():
total_reconciled_amount += reconciled_amount
total_amount += amount
# Compute matched percentage for each account.
if total_amount and aml_account_id not in reconciled_percentage_per_move[aml_column_group_index][aml_move_id]:
# Lines being on reconciled moves but not reconciled with any liquidity move must be valued at the
# percentage of what is actually paid.
reconciled_percentage = total_reconciled_amount / total_amount
aml_balance *= reconciled_percentage
elif not total_amount and aml_account_id in reconciled_percentage_per_move[aml_column_group_index][aml_move_id]:
# The total amount to reconcile is 0. In that case, only add entries being on these accounts. Otherwise,
# this special case will lead to an unexplained difference equivalent to the reconciled amount on this
# account.
# E.g:
#
# Liquidity move:
# Account | Debit | Credit
# --------------------------------------
# Bank | | 100
# Receivable | 100 |
#
# Reconciled move: <- reconciled_amount=100, total_amount=0.0
# Account | Debit | Credit
# --------------------------------------
# Receivable | | 200
# Receivable | 200 | <- Only the reconciled part of this entry must be added.
aml_balance = -reconciled_percentage_per_move[aml_column_group_index][aml_move_id][aml_account_id][0]
else:
# Others lines are not considered.
continue
reconciled_aml_per_account.setdefault(aml_account_id, {})
reconciled_aml_per_account[aml_account_id].setdefault(aml_column_group_index, {
'column_group_index': aml_column_group_index,
'account_id': aml_account_id,
'account_code': aml_account_code,
'account_name': aml_account_name,
'account_account_type': aml_account_account_type,
'account_tag_id': aml_account_tag_id,
'balance': 0.0,
})
reconciled_aml_per_account[aml_account_id][aml_column_group_index]['balance'] -= aml_balance
return list(reconciled_aml_per_account.values())
# -------------------------------------------------------------------------
# COLUMNS / LINES
# -------------------------------------------------------------------------
def _get_layout_data(self):
# Indentation of the following dict reflects the structure of the report.
return {
'opening_balance': {'name': _('Cash and cash equivalents, beginning of period'), 'level': 0},
'net_increase': {'name': _('Net increase in cash and cash equivalents'), 'level': 0, 'unfolded': True},
'operating_activities': {'name': _('Cash flows from operating activities'), 'level': 2, 'parent_line_id': 'net_increase', 'class': 'fw-bold', 'unfolded': True},
'advance_payments_customer': {'name': _('Advance Payments received from customers'), 'level': 4, 'parent_line_id': 'operating_activities'},
'received_operating_activities': {'name': _('Cash received from operating activities'), 'level': 4, 'parent_line_id': 'operating_activities'},
'advance_payments_suppliers': {'name': _('Advance payments made to suppliers'), 'level': 4, 'parent_line_id': 'operating_activities'},
'paid_operating_activities': {'name': _('Cash paid for operating activities'), 'level': 4, 'parent_line_id': 'operating_activities'},
'investing_activities': {'name': _('Cash flows from investing & extraordinary activities'), 'level': 2, 'parent_line_id': 'net_increase', 'class': 'fw-bold', 'unfolded': True},
'investing_activities_cash_in': {'name': _('Cash in'), 'level': 4, 'parent_line_id': 'investing_activities'},
'investing_activities_cash_out': {'name': _('Cash out'), 'level': 4, 'parent_line_id': 'investing_activities'},
'financing_activities': {'name': _('Cash flows from financing activities'), 'level': 2, 'parent_line_id': 'net_increase', 'class': 'fw-bold', 'unfolded': True},
'financing_activities_cash_in': {'name': _('Cash in'), 'level': 4, 'parent_line_id': 'financing_activities'},
'financing_activities_cash_out': {'name': _('Cash out'), 'level': 4, 'parent_line_id': 'financing_activities'},
'unclassified_activities': {'name': _('Cash flows from unclassified activities'), 'level': 2, 'parent_line_id': 'net_increase', 'class': 'fw-bold', 'unfolded': True},
'unclassified_activities_cash_in': {'name': _('Cash in'), 'level': 4, 'parent_line_id': 'unclassified_activities'},
'unclassified_activities_cash_out': {'name': _('Cash out'), 'level': 4, 'parent_line_id': 'unclassified_activities'},
'closing_balance': {'name': _('Cash and cash equivalents, closing balance'), 'level': 0},
}
def _get_layout_line(self, report, options, layout_line_id, layout_line_data, report_data):
line_id = report._get_generic_line_id(None, None, markup=layout_line_id)
unfoldable = 'aml_groupby_account' in report_data[layout_line_id] if layout_line_id in report_data else False
column_values = []
for column in options['columns']:
expression_label = column['expression_label']
column_group_index = column['column_group_index']
value = report_data[layout_line_id][expression_label].get(column_group_index, 0.0) if layout_line_id in report_data else 0.0
column_values.append(report._build_column_data(value, column, options=options))
return AccountReportLineData(
id=line_id,
name=layout_line_data['name'],
level=layout_line_data['level'],
css_class=layout_line_data.get('class', ''),
columns=column_values,
unfoldable=unfoldable,
unfolded=line_id in options['unfolded_lines'] or layout_line_data.get('unfolded') or (options.get('unfold_all') and unfoldable),
)
def _get_aml_line(self, report, options, aml_data):
parent_line_id = report._get_generic_line_id(None, None, aml_data['parent_line_id'])
line_id = report._get_generic_line_id('account.account', aml_data['account_id'], parent_line_id=parent_line_id)
column_values = []
for column in options['columns']:
expression_label = column['expression_label']
column_group_index = column['column_group_index']
value = aml_data[expression_label].get(column_group_index, 0.0)
column_values.append(report._build_column_data(value, column, options=options))
return AccountReportLineData(
id=line_id,
name=f"{aml_data['account_code']} {aml_data['account_name']}" if aml_data['account_code'] else aml_data['account_name'],
caret_options='account.account',
level=aml_data['level'],
parent_id=parent_line_id,
columns=column_values,
)
def _get_unexplained_difference_line(self, report, options, report_data):
unexplained_difference = False
column_values = []
for column in options['columns']:
expression_label = column['expression_label']
column_group_index = column['column_group_index']
opening_balance = report_data['opening_balance'][expression_label].get(column_group_index, 0.0) if 'opening_balance' in report_data else 0.0
closing_balance = report_data['closing_balance'][expression_label].get(column_group_index, 0.0) if 'closing_balance' in report_data else 0.0
net_increase = report_data['net_increase'][expression_label].get(column_group_index, 0.0) if 'net_increase' in report_data else 0.0
balance = closing_balance - opening_balance - net_increase
if not self.env.company.currency_id.is_zero(balance):
unexplained_difference = True
column_values.append(report._build_column_data(
balance,
{
'figure_type': 'monetary',
'expression_label': 'balance',
},
options=options,
))
if unexplained_difference:
return AccountReportLineData(
id=report._get_generic_line_id(None, None, markup='unexplained_difference'),
name=self.env._("Unexplained Difference"),
level=1,
columns=column_values,
)

View File

@@ -0,0 +1,84 @@
from odoo import models
from odoo.addons.account.models.chart_template import template
class AccountChartTemplate(models.AbstractModel):
_inherit = 'account.chart.template'
def _pre_reload_data(self, company, template_data, data, force_create=True, force_update=False):
# EXTENDS account
super()._pre_reload_data(company, template_data, data, force_create=force_create, force_update=force_update)
if force_update:
return
# A return type is a single record shared by every company, so the accounts it settles on are
# configuration rather than master data. Reloading the chart must not undo them.
for xmlid, values in data.get('account.return.type', {}).items():
return_type = self.ref(xmlid, raise_if_not_found=False)
if not return_type:
continue
for field_name in ('advance_tax_payment_account_id', 'tax_payable_account_id', 'tax_receivable_account_id'):
if field_name in values and return_type.with_company(company)[field_name]:
del values[field_name]
def _instantiate_foreign_taxes(self, country, company):
# EXTENDS account
res = super()._instantiate_foreign_taxes(country, company)
self._setup_foreign_closing_accounts(country, company)
return res
def _setup_foreign_closing_accounts(self, country, company):
""" Give the returns of a foreign VAT registration their own settlement accounts."""
foreign_return_types = self.env['account.return.type'].sudo().search([
('country_id', '=', country.id),
]).filtered('is_tax_return_type')
domestic_return_type = self.env['account.return.type'].sudo().search([
('country_id', '=', company.account_fiscal_country_id.id),
]).filtered('is_tax_return_type')[:1]
if not foreign_return_types or not domestic_return_type:
return
field_and_names = (
('tax_payable_account_id', self.env._("Foreign tax account payable (%s)", country.code)),
('tax_receivable_account_id', self.env._("Foreign tax account receivable (%s)", country.code)),
('advance_tax_payment_account_id', self.env._("Foreign advance tax payment account (%s)", country.code)),
)
for field_name, account_name in field_and_names:
if any(foreign_return_types.with_company(company).mapped(field_name)):
continue
domestic_account = domestic_return_type.with_company(company)[field_name]
if not domestic_account:
continue
foreign_return_types.with_company(company)[field_name] = self._create_foreign_account(company, domestic_account, account_name)
@template(model='account.journal')
def _get_account_reports_journal(self, template_code):
"""Add a journal for the tax returns."""
return {
'tax_returns': {
'name': self.env._("Tax Returns"),
'type': 'general',
'code': 'TAX',
'show_on_dashboard': False,
},
}
@template(model='res.company')
def _get_account_reports_res_company(self, chart_template):
"""Make sure the tax return journal is set on the company.
This is necessary when the CoA was already installed before this module.
The method is called in the post-init hook of this module.
"""
company = self.env.company
return {
company.id: {
'account_tax_return_journal_id': company.account_tax_return_journal_id.id or 'tax_returns',
},
}
@template(model='account.return.type')
def _instantiate_returns_on_loading(self, chart_template):
# Make sure all appropriate returns are directly generated when installing a CoA
self.env['account.return.type'].sudo()._generate_or_refresh_all_returns(self.env.company.root_id)

View File

@@ -0,0 +1,41 @@
from odoo import models, _
class CustomerStatementCustomHandler(models.AbstractModel):
_name = 'account.customer.statement.report.handler'
_inherit = 'account.partner.ledger.report.handler'
_description = 'Customer Statement Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options)
options['buttons'].append({
'name': _('Send'),
'action': 'action_send_statements',
'sequence': 90,
'always_show': True,
})
options['custom_display_config']['css_custom_class'] += ' customer_statement'
if self.env.ref('account_reports.pdf_export_main_customer_report', raise_if_not_found=False):
options['custom_display_config'].setdefault('pdf_export', {})['pdf_export_main'] = 'account_reports.pdf_export_main_customer_report'
def _get_subformulas_rules(self):
return super()._get_subformulas_rules() | {
'amount': {'field': 'balance', 'from_beginning': True}
}
def action_send_statements(self, options):
template = self.env.ref('account_reports.email_template_customer_statement', False)
partners = self.env['res.partner'].browse(options.get('partner_ids', []))
return {
'name': _("Send %s Statement", partners.name) if len(partners) == 1 else _("Send Customer Statements"),
'type': 'ir.actions.act_window',
'views': [[False, 'form']],
'res_model': 'account.report.send',
'target': 'new',
'context': {
'default_mail_template_id': template.id if template else False,
'default_report_options': options,
},
}

View File

@@ -0,0 +1,692 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import calendar
from collections import defaultdict
from dateutil.relativedelta import relativedelta
from psycopg2 import sql
from odoo import models, fields, _, api, Command
from odoo.exceptions import UserError
from odoo.tools import groupby, SQL
from odoo.addons.account_accountant.models.account_move import DEFERRED_DATE_MIN, DEFERRED_DATE_MAX
from odoo.addons.account_reports.utils.report_data_objects import AccountReportLineData
class AccountDeferredReportHandler(models.AbstractModel):
_name = 'account.deferred.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Deferred Expense Report Custom Handler'
def _get_deferred_report_type(self):
raise NotImplementedError("This method is not implemented in the deferred report handler.")
############################################
# DEFERRED COMMON (DISPLAY AND GENERATION) #
############################################
def _get_domain_fully_inside_period(self, options):
return [ # Exclude if entirely inside the period
'!', '&', '&', '&', '&', '&', '&', '&',
('deferred_start_date', '!=', False),
('deferred_end_date', '!=', False),
('deferred_start_date', '>=', options['date']['date_from']),
('deferred_start_date', '<=', options['date']['date_to']),
('deferred_end_date', '>=', options['date']['date_from']),
('deferred_end_date', '<=', options['date']['date_to']),
('move_id.date', '>=', options['date']['date_from']),
('move_id.date', '<=', options['date']['date_to']),
]
def _get_domain(self, report, options, filter_already_generated=False, filter_not_started=False):
domain = report._get_options_domain(options, "from_beginning")
account_types = ('expense', 'expense_depreciation', 'expense_direct_cost') if self._get_deferred_report_type() == 'expense' else ('income', 'income_other')
domain += [
('account_id.account_type', 'in', account_types),
('deferred_start_date', '!=', False),
('deferred_end_date', '!=', False),
('deferred_end_date', '>=', options['date']['date_from']),
('move_id.date', '<=', options['date']['date_to']),
]
domain += self._get_domain_fully_inside_period(options)
if filter_already_generated:
# Avoid regenerating already generated deferrals
domain += [
('deferred_end_date', '>=', options['date']['date_from']),
'!',
('move_id.deferred_move_ids', 'any', [
('date', '=', options['date']['date_to']),
'|',
('state', '=', 'posted'), # Either posted
'&', # Or autoposted in the future
('auto_post', '=', 'at_date'),
('date', '>=', fields.Date.context_today(self)),
])
]
if filter_not_started:
domain += [('deferred_start_date', '>', options['date']['date_to'])]
return domain
@api.model
def _get_select(self, options):
account_name = self.env['account.account']._field_to_sql('account_move_line__account_id', 'name')
return [
SQL("account_move_line.id AS line_id"),
SQL("account_move_line.account_id AS account_id"),
SQL("account_move_line.partner_id AS partner_id"),
SQL("account_move_line.product_id AS product_id"),
SQL("account_move_line__product_template_id.categ_id AS product_category_id"),
SQL("account_move_line.name AS line_name"),
SQL("account_move_line.deferred_start_date AS deferred_start_date"),
SQL("account_move_line.deferred_end_date AS deferred_end_date"),
SQL("account_move_line.deferred_end_date - account_move_line.deferred_start_date AS diff_days"),
SQL("account_move_line.balance AS balance"),
SQL("account_move_line.analytic_distribution AS analytic_distribution"),
SQL("account_move_line__move_id.id as move_id"),
SQL("account_move_line__move_id.name AS move_name"),
SQL("""
NOT (
account_move_line.deferred_end_date >= %(report_date_from)s
AND
NOT EXISTS (
SELECT 1
FROM account_move_deferred_rel AS amdr
LEFT JOIN account_move AS am ON amdr.deferred_move_id = am.id
WHERE amdr.original_move_id = account_move_line.move_id
AND am.date = %(report_date_to)s
AND (
am.state = 'posted'
OR (am.auto_post = 'at_date' AND am.date >= %(today)s)
)
)
) AS is_already_generated
""",
report_date_from=options['date']['date_from'],
report_date_to=options['date']['date_to'],
today=fields.Date.context_today(self),
),
SQL("%s AS account_name", account_name),
]
def _get_lines(self, report, options, filter_already_generated=False):
if 'report_deferred_lines' not in self.env.cr.cache:
self._fetch_lines(report, options, filter_already_generated)
if not filter_already_generated:
# No more filtering needed, we can reuse the cached result
return self.env.cr.cache['report_deferred_lines'].values()
else:
# Filter the cached result to only keep the lines that are not already generated
cached_lines = self.env.cr.cache['report_deferred_lines'].values()
return [cached_line for cached_line in cached_lines if not cached_line['is_already_generated']]
def _fetch_lines(self, report, options, filter_already_generated):
"""Fetch the lines that need to be deferred from the DB and store them in the cache for later reuse"""
domain = self._get_domain(report, options, filter_already_generated)
query = report._get_report_query(options, domain=domain, date_scope='from_beginning')
select_clause = SQL(', ').join(self._get_select(options))
query = SQL(
"""
SELECT %(select_clause)s
FROM %(table_references)s
LEFT JOIN product_product AS account_move_line__product_id ON account_move_line.product_id = account_move_line__product_id.id
LEFT JOIN product_template AS account_move_line__product_template_id ON account_move_line__product_id.product_tmpl_id = account_move_line__product_template_id.id
WHERE %(search_condition)s
ORDER BY account_move_line.deferred_start_date, account_move_line.id
""",
select_clause=select_clause,
table_references=query.from_clause,
search_condition=query.where_clause,
)
self.env.cr.execute(query)
# Cache the result so that it can be reused to check whether a warning banner should be shown
# only if it's the generic query (so without filtering already generated deferrals)
self.env.cr.cache['report_deferred_lines'] = {
r['line_id']: r for r in self.env.cr.dictfetchall()
}
@api.model
def _get_grouping_fields_deferred_lines(self, filter_already_generated=False, grouping_field='account_id'):
return (grouping_field,)
@api.model
def _group_by_deferred_fields(self, line, filter_already_generated=False, grouping_field='account_id'):
return tuple(line[k] for k in self._get_grouping_fields_deferred_lines(filter_already_generated, grouping_field))
@api.model
def _get_grouping_fields_deferral_lines(self):
return ('deferred_account_id',)
@api.model
def _group_by_deferral_fields(self, line):
return tuple(line[k] for k in self._get_grouping_fields_deferral_lines())
@api.model
def _group_deferred_amounts_by_grouping_field(self, deferred_amounts_by_line, periods, is_reverse, filter_already_generated=False, grouping_field='account_id'):
"""
Groups the deferred amounts by account and computes the totals for each account for each period.
And the total for all accounts for each period.
E.g. (where period1 = (date1, date2, label1), period2 = (date2, date3, label2), ...)
{
self._get_grouping_keys_deferred_lines(): {
'account_id': account1, 'amount_total': 600, period_1: 200, period_2: 400
},
self._get_grouping_keys_deferred_lines(): {
'account_id': account2, 'amount_total': 700, period_1: 300, period_2: 400
},
}, {'totals_aggregated': 1300, period_1: 500, period_2: 800}
"""
deferred_amounts_by_line = groupby(deferred_amounts_by_line, key=lambda x: self._group_by_deferred_fields(x, filter_already_generated, grouping_field))
totals_per_key = {} # {key: {**self._get_grouping_fields_deferral_lines(), total, before, current, later}}
totals_aggregated_by_period = {period: 0 for period in periods + ['totals_aggregated']}
sign = 1 if is_reverse else -1
for key, lines_per_key in deferred_amounts_by_line:
lines_per_key = list(lines_per_key)
current_key_totals = self._get_current_key_totals_dict(lines_per_key, sign)
totals_aggregated_by_period['totals_aggregated'] += current_key_totals['amount_total']
for period in periods:
current_key_totals[period] = sign * sum(line[period] for line in lines_per_key)
totals_aggregated_by_period[period] += self.env.company.currency_id.round(current_key_totals[period])
totals_per_key[key] = current_key_totals
return totals_per_key, totals_aggregated_by_period
###########################
# DEFERRED REPORT DISPLAY #
###########################
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
options_per_col_group = report._split_options_per_column_group(options)
for column_dict in options['columns']:
column_options = options_per_col_group[column_dict['column_group_index']]
column_dict['name'] = column_options['date']['string']
column_dict['date_from'] = column_options['date']['date_from']
column_dict['date_to'] = column_options['date']['date_to']
options['columns'] = list(reversed(options['columns']))
total_column = [{
**options['columns'][0],
'name': _('Total'),
'expression_label': 'total',
'date_from': DEFERRED_DATE_MIN,
'date_to': DEFERRED_DATE_MAX,
}]
not_started_column = [{
**options['columns'][0],
'name': _('Not Started'),
'expression_label': 'not_started',
'date_from': options['columns'][-1]['date_to'],
'date_to': DEFERRED_DATE_MAX,
}]
before_column = [{
**options['columns'][0],
'name': _('Before'),
'expression_label': 'before',
'date_from': DEFERRED_DATE_MIN,
'date_to': fields.Date.to_string(fields.Date.to_date(options['columns'][0]['date_from']) - relativedelta(days=1)),
}]
report_date_to = fields.Date.to_date(options['columns'][-1]['date_to'])
# Split the "Later to be recognized" column into:
# - short-term (within 12 months)
# - long-term (after 12 months) part
twelve_months_later = report_date_to + relativedelta(years=1)
later_columns = [
{
**options['columns'][0],
'name': _('≤ 12 Months'),
'expression_label': 'within_year',
'date_from': fields.Date.to_string(report_date_to + relativedelta(days=1)),
'date_to': fields.Date.to_string(twelve_months_later),
},
{
**options['columns'][0],
'name': _('> 12 Months'),
'expression_label': 'after_year',
'date_from': fields.Date.to_string(twelve_months_later + relativedelta(days=1)),
'date_to': DEFERRED_DATE_MAX,
},
]
recognized_column = [{
**options['columns'][0],
'name': _('Recognized'),
'expression_label': 'recognized',
'date_from': DEFERRED_DATE_MIN,
'date_to': options['columns'][-1]['date_to'], # Covers up to end of current period
}]
options['columns'] = total_column + not_started_column + before_column + options['columns'] + recognized_column + later_columns
options['column_headers'] = []
options['deferred_report_type'] = self._get_deferred_report_type()
options['deferred_grouping_field'] = previous_options.get('deferred_grouping_field') or 'account_id'
if (
self._get_deferred_report_type() == 'expense' and self.env.company.generate_deferred_expense_entries_method == 'manual'
or self._get_deferred_report_type() == 'revenue' and self.env.company.generate_deferred_revenue_entries_method == 'manual'
):
options['buttons'].append({'name': _('Generate entry'), 'action': 'action_generate_entry', 'sequence': 80, 'always_show': True})
options['custom_display_config'] = {
'templates': {
'AccountReportFilters': 'account_reports.DeferredFilters',
},
}
def action_audit_cell(self, options, params):
""" Open a list of invoices/bills and/or deferral entries for the clicked cell in a deferred report.
Specifically, we show the following lines, grouped by their journal entry, filtered by the column date bounds:
- Total: Lines of all invoices/bills being deferred in the current period
- Not Started: Lines of all deferral entries for which the original invoice/bill date is before or in the
current period, but the deferral only starts after the current period, as well as the lines of
their original invoices/bills
- Before: Lines of all deferral entries with a date before the current period, created by invoices/bills also
being deferred in the current period, as well as the lines of their original invoices/bills
- Current: Lines of all deferral entries in the current period, as well as these of their original
invoices/bills
- Later: Lines of all deferral entries with a date after the current period, created by invoices/bills also
being deferred in the current period, as well as the lines of their original invoices/bills
:param dict options: the report's `options`
:param dict params: a dict containing:
`calling_line_dict_id`: line id containing the optional account of the cell
`column_group_id`: the column group id of the cell
`expression_label`: the expression label of the cell
"""
report = self.env['account.report'].browse(options['report_id'])
column_values = next(
(column for column in options['columns'] if (
column['column_group_index'] == params.get('column_group_index')
and column['expression_label'] == params.get('expression_label')
)),
None
)
if not column_values:
return
column_date_from = fields.Date.to_date(column_values['date_from'])
column_date_to = fields.Date.to_date(column_values['date_to'])
report_date_from = fields.Date.to_date(options['date']['date_from'])
report_date_to = fields.Date.to_date(options['date']['date_to'])
# Corrections for comparisons
if column_values['expression_label'] == 'not_started':
# Not Started period starts one day after `report_date_to`
column_date_from = report_date_to + relativedelta(days=1)
if column_values['expression_label'] == 'before':
# Before period ends one day before `report_date_from`
column_date_to = report_date_from - relativedelta(days=1)
# calling_line_dict_id is of the format `~account.report~15|~account.account~25`
_grouping_model, grouping_record_id = report._get_model_info_from_id(params.get('calling_line_dict_id'))
# Find the original lines to be deferred in the report period
original_move_lines_domain = self._get_domain(
report, options, filter_not_started=column_values['expression_label'] == 'not_started'
)
if grouping_record_id:
# We're auditing a specific account, so we only want moves containing this account
original_move_lines_domain.append((options['deferred_grouping_field'], '=', grouping_record_id))
# We're getting all lines from the concerned moves. They are filtered later for flexibility.
original_moves = self.env['account.move.line'].search(original_move_lines_domain).move_id
domain = [
# For the Total period only show the original move lines
'&',
('move_id', 'in', original_moves.ids),
('deferred_end_date', '>=', report_date_from),
]
# Show both the original move lines and deferral move lines for all other periods
if column_values['expression_label'] != 'total' and original_moves.deferred_move_ids:
domain = ['|'] + [('move_id', 'in', original_moves.deferred_move_ids.ids)] + domain
if column_values['expression_label'] == 'not_started':
domain += [('deferred_start_date', '>=', column_date_from)]
else:
# If in manually & grouped mode, and deferrals have not yet been generated
# so no move with `date` set => instead show the candidates original deferred moves that
# will be deferred upon clicking the button. If totally/partially generated, we'll just
# use the `date` filter which will include both the originals and deferrals.
if not original_moves.deferred_move_ids:
domain += [
('deferred_start_date', '<=', column_date_to),
('deferred_end_date', '>=', column_date_from),
]
else:
domain += [
('date', '>=', column_date_from),
('date', '<=', column_date_to),
]
domain += self._get_domain_fully_inside_period(options)
return {
'type': 'ir.actions.act_window',
'name': _('Deferred Entries'),
'res_model': 'account.move.line',
'domain': domain,
'views': [(self.env.ref('account_accountant.view_deferred_entries_tree').id, 'list'), (False, 'pivot'), (False, 'graph'), (False, 'kanban')],
# Most filters are set here to allow auditing flexibility to the user
'context': {
'search_default_pl_accounts': True,
f'search_default_{options["deferred_grouping_field"]}': grouping_record_id,
'expand': True,
},
}
def _caret_options_initializer(self):
return {
'deferred_caret': [
{'name': _("Journal Items"), 'action': 'open_journal_items'},
],
}
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
if (
self._get_deferred_report_type() == 'expense' and self.env.company.generate_deferred_expense_entries_method == 'manual'
or self._get_deferred_report_type() == 'revenue' and self.env.company.generate_deferred_revenue_entries_method == 'manual'
):
already_generated = self.env['account.move'].search_count(
report._get_generated_deferral_entries_domain(options)
)
# This will trigger a second _get_lines call, however the first one was cached, so we just need to filter again on the cache (see _get_lines)
moves_lines_to_generate, __, __, __, __ = self._get_moves_to_defer(options)
if moves_lines_to_generate and already_generated:
warnings['account_reports.deferred_report_warning_partially_generated'] = {'alert_type': 'warning'}
elif moves_lines_to_generate:
warnings['account_reports.deferred_report_warning_never_generated'] = {'alert_type': 'warning'}
elif already_generated:
warnings['account_reports.deferred_report_info_fully_generated'] = {'alert_type': 'info'}
def open_journal_items(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
record_model, record_id = report._get_model_info_from_id(params.get('line_id'))
domain = self._get_domain(report, options)
if record_model == 'account.account' and record_id:
domain += [('account_id', '=', record_id)]
elif record_model == 'product.product' and record_id:
domain += [('product_id', '=', record_id)]
elif record_model == 'product.category' and record_id:
domain += [('product_category_id', '=', record_id)]
return {
'type': 'ir.actions.act_window',
'name': _("Deferred Entries"),
'res_model': 'account.move.line',
'domain': domain,
'views': [(self.env.ref('account_accountant.view_deferred_entries_tree').id, 'list')],
'context': {
'search_default_group_by_move': True,
'expand': True,
}
}
def _dynamic_lines_generator(self, report, options, all_column_groups_expression_totals, warnings=None):
def get_columns(totals):
columns = []
for column in options['columns']:
column = report._build_column_data(
totals[
fields.Date.to_date(column['date_from']),
fields.Date.to_date(column['date_to']),
column['expression_label']
],
column,
options=options,
currency=self.env.company.currency_id,
)
column.auditable = True
columns.append(column)
return columns
lines = self._get_lines(report, options)
periods = [
(
fields.Date.from_string(column['date_from']),
fields.Date.from_string(column['date_to']),
column['expression_label'],
)
for column in options['columns']
]
deferred_amounts_by_line = self.env['account.move']._get_deferred_amounts_by_line(lines, periods, self._get_deferred_report_type())
totals_per_grouping_field, totals_all_grouping_field = self._group_deferred_amounts_by_grouping_field(
deferred_amounts_by_line=deferred_amounts_by_line,
periods=periods,
is_reverse=self._get_deferred_report_type() == 'expense',
filter_already_generated=False,
grouping_field=options['deferred_grouping_field'],
)
report_lines = []
grouping_model = self.env['account.move.line'][options['deferred_grouping_field']]._name
for totals_grouping_field in totals_per_grouping_field.values():
grouping_record = self.env[grouping_model].browse(totals_grouping_field[options['deferred_grouping_field']])
grouping_field_description = self.env['account.move.line'][options['deferred_grouping_field']]._description
if options['deferred_grouping_field'] == 'product_id':
grouping_field_description = _("Product")
grouping_name = grouping_record.display_name or _("(No %s)", grouping_field_description)
report_lines.append((0, AccountReportLineData(
id=report._get_generic_line_id(grouping_model, grouping_record.id),
name=grouping_name,
caret_options='deferred_caret',
level=1,
columns=get_columns(totals_grouping_field),
)))
if totals_per_grouping_field:
report_lines.append((0, AccountReportLineData(
id=report._get_generic_line_id(None, None, markup='total'),
name=self.env._("Total"),
level=1,
columns=get_columns(totals_all_grouping_field),
)))
return report_lines
#######################
# DEFERRED GENERATION #
#######################
def action_generate_entry(self, options):
new_deferred_moves = self._generate_deferral_entry(options)
report = self.env['account.report'].browse(options['report_id'])
domain = report._get_generated_deferral_entries_domain(options)
already_generated = self.env['account.move'].search_count(domain, limit=1)
if new_deferred_moves or already_generated:
return report.open_deferral_entries(options, {})
raise UserError(_("No entry to generate."))
def _get_moves_to_defer(self, options):
date_from = fields.Date.to_date(DEFERRED_DATE_MIN)
date_to = fields.Date.from_string(options['date']['date_to'])
if date_to.day != calendar.monthrange(date_to.year, date_to.month)[1]:
raise UserError(_("You cannot generate entries for a period that does not end at the end of the month."))
options['all_entries'] = False # We only want to create deferrals for posted moves
report = self.env["account.report"].browse(options["report_id"])
self.env['account.move.line'].flush_model()
lines = self._get_lines(report, options, filter_already_generated=True)
deferral_entry_period = self.env['account.report']._build_date_dict(options, date_from, date_to, period_type='month')
ref = self.env._("Grouped Deferral Entry of %s", deferral_entry_period['string'])
ref_rev = self.env._("Reversal of Grouped Deferral Entry of %s", deferral_entry_period['string'])
deferred_account = self.env.company.deferred_expense_account_id if self._get_deferred_report_type() == 'expense' else self.env.company.deferred_revenue_account_id
move_lines, original_move_ids = self._get_deferred_lines(lines, deferred_account, (date_from, date_to, 'current'), self._get_deferred_report_type() == 'expense', ref)
return move_lines, original_move_ids, ref, ref_rev, date_to
def _generate_deferral_entry(self, options):
journal = self.env.company.deferred_expense_journal_id if self._get_deferred_report_type() == "expense" else self.env.company.deferred_revenue_journal_id
if not journal:
raise UserError(_("Please set the deferred journal in the accounting settings."))
move_lines, original_move_ids, ref, ref_rev, date_to = self._get_moves_to_defer(options)
if self.env.company._get_violated_lock_dates(date_to, False, journal):
raise UserError(_("You cannot generate entries for a period that is locked."))
if not move_lines:
return self.env['account.move']
deferred_move = self.env['account.move'].with_context(skip_account_deprecation_check=True).create({
'move_type': 'entry',
'deferred_original_move_ids': [Command.set(original_move_ids)],
'journal_id': journal.id,
'date': date_to,
'auto_post': 'at_date',
'ref': ref,
})
# We write the lines after creation, to make sure the `deferred_original_move_ids` is set.
# This way we can avoid adding taxes for deferred moves.
deferred_move.write({'line_ids': move_lines})
reverse_move = deferred_move._reverse_moves()
reverse_move.write({
'date': deferred_move.date + relativedelta(days=1),
'ref': ref_rev,
})
reverse_move.line_ids.name = ref_rev
new_deferred_moves = deferred_move + reverse_move
# We create the relation (original deferred move, deferral entry)
# using SQL. This avoids a MemoryError using the ORM which will
# load huge amounts of moves in memory for nothing
self.env.cr.execute_values(sql.SQL("""
INSERT INTO account_move_deferred_rel(original_move_id, deferred_move_id)
VALUES %s
ON CONFLICT DO NOTHING
"""), [
(original_move_id, deferral_move.id)
for original_move_id in original_move_ids
for deferral_move in new_deferred_moves
])
new_deferred_moves.invalidate_recordset()
new_deferred_moves._post(soft=True)
return new_deferred_moves
@api.model
def _get_current_key_totals_dict(self, lines_per_key, sign):
return {
'account_id': lines_per_key[0]['account_id'],
'deferred_account_id': lines_per_key[0].get('deferred_account_id'),
'product_id': lines_per_key[0]['product_id'],
'product_category_id': lines_per_key[0]['product_category_id'],
'amount_total': sign * sum(line['balance'] for line in lines_per_key),
'move_ids': {line['move_id'] for line in lines_per_key},
}
@api.model
def _get_deferred_lines(self, lines, deferred_account, period, is_reverse, ref):
"""
Returns a list of Command objects to create the deferred lines of a single given period.
And the move_ids of the original lines that created these deferred
(to keep track of the original invoice in the deferred entries).
"""
# Resolve the deferred account to use for each original account: the one set on the
# account itself if any, otherwise the generic account from the accounting settings.
accounts = self.env['account.account'].browse({line['account_id'] for line in lines})
deferred_account_per_account = {
account.id: account.deferred_account_id or deferred_account
for account in accounts
}
if not all(deferred_account_per_account.values()):
raise UserError(_("Please set a deferred account on the related account or in the accounting settings."))
for line in lines:
line['deferred_account_id'] = deferred_account_per_account[line['account_id']].id
deferred_amounts_by_line = self.env['account.move']._get_deferred_amounts_by_line(lines, [period], is_reverse)
for line in deferred_amounts_by_line:
line['deferred_account_id'] = deferred_account_per_account[line['account_id']].id
deferred_amounts_by_key, deferred_amounts_totals = self._group_deferred_amounts_by_grouping_field(deferred_amounts_by_line, [period], is_reverse, filter_already_generated=True)
totals_aggregated = deferred_amounts_totals['totals_aggregated']
if totals_aggregated == deferred_amounts_totals[period]:
return [], set()
# compute analytic distribution to populate on deferred lines
# structure: {self._get_grouping_keys_deferred_lines(): [analytic distribution]}
# dict of keys: self._get_grouping_keys_deferred_lines()
# values: dict of keys: "account.analytic.account.id" (string)
# values: float
anal_dist_by_key = defaultdict(lambda: defaultdict(float))
# using another var for the analytic distribution of the deferral account
deferred_anal_dist = defaultdict(lambda: defaultdict(float))
for line in lines:
if not line['analytic_distribution']:
continue
# Analytic distribution should be computed from the lines with the same _get_grouping_keys_deferred_lines(), except for
# the deferred line with the deferral account which will use _get_grouping_fields_deferral_lines()
sign = 1 if is_reverse else -1
key_amount = deferred_amounts_by_key.get(self._group_by_deferred_fields(line, True))
total_amount = key_amount.get('amount_total')
key_ratio = sign * line['balance'] / total_amount if total_amount else 0
full_ratio = sign * line['balance'] / totals_aggregated if totals_aggregated else 0
for account_id, distribution in line['analytic_distribution'].items():
anal_dist_by_key[self._group_by_deferred_fields(line, True)][account_id] += distribution * key_ratio
deferred_anal_dist[self._group_by_deferral_fields(line)][account_id] += distribution * full_ratio
remaining_balance = 0
deferred_lines = []
original_move_ids = set()
for key, line in deferred_amounts_by_key.items():
for balance in (-line['amount_total'], line[period]):
if balance != 0 and line[period] != line['amount_total']:
original_move_ids |= line['move_ids']
deferred_balance = self.env.company.currency_id.round((1 if is_reverse else -1) * balance)
deferred_lines.append(
Command.create(
self.env['account.move.line']._get_deferred_lines_values(
account_id=line['account_id'],
balance=deferred_balance,
ref=ref,
analytic_distribution=anal_dist_by_key[key] or False,
line=line,
)
)
)
remaining_balance += deferred_balance
grouped_by_key = {
key: list(value)
for key, value in groupby(
deferred_amounts_by_key.values(),
key=self._group_by_deferral_fields,
)
}
deferral_lines = []
for key, lines_per_key in grouped_by_key.items():
balance = 0
for line in lines_per_key:
if line[period] != line['amount_total']:
balance += self.env.company.currency_id.round((1 if is_reverse else -1) * (line['amount_total'] - line[period]))
deferral_lines.append(
Command.create(
self.env['account.move.line']._get_deferred_lines_values(
account_id=lines_per_key[0]['deferred_account_id'],
balance=balance,
ref=ref,
analytic_distribution=deferred_anal_dist[key] or False,
line=lines_per_key[0],
)
)
)
remaining_balance += balance
if not self.env.company.currency_id.is_zero(remaining_balance):
deferral_lines.append(
Command.create({
'account_id': deferred_account.id,
'balance': -remaining_balance,
'name': ref,
})
)
return deferred_lines + deferral_lines, original_move_ids
class AccountDeferredExpenseReportHandler(models.AbstractModel):
_name = 'account.deferred.expense.report.handler'
_inherit = ['account.deferred.report.handler']
_description = 'Deferred Expense Custom Handler'
def _get_deferred_report_type(self):
return 'expense'
class AccountDeferredRevenueReportHandler(models.AbstractModel):
_name = 'account.deferred.revenue.report.handler'
_inherit = ['account.deferred.report.handler']
_description = 'Deferred Revenue Custom Handler'
def _get_deferred_report_type(self):
return 'revenue'

View File

@@ -0,0 +1,10 @@
from odoo import models
class AccountFiscalPosition(models.Model):
_inherit = 'account.fiscal.position'
def action_create_foreign_taxes(self):
# EXTENDS account
super().action_create_foreign_taxes()
self.env['account.return.type']._generate_or_refresh_all_returns(self.company_id.root_id)

View File

@@ -0,0 +1,96 @@
from odoo import models, fields
from odoo.tools import SQL
class AccountFollowupCustomHandler(models.AbstractModel):
_name = 'account.followup.report.handler'
_inherit = 'account.partner.ledger.report.handler'
_description = 'Follow-Up Report Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options)
options['buttons'].append({
'name': self.env._('Send'),
'action': 'action_send_follow_up',
'sequence': 100,
'always_show': True,
})
options['custom_display_config'].setdefault('components', {})['AccountReportLineCell'] = 'PartnerLedgerFollowupLineCell'
if self.env.ref('account_reports.pdf_export_main_customer_report', raise_if_not_found=False):
options['custom_display_config'].setdefault('pdf_export', {})['pdf_export_main'] = 'account_reports.pdf_export_main_customer_report'
if len(options['partner_ids']) == 1:
options['ignore_totals_below_sections'] = True
options['hide_partner_totals'] = True
if options['report_id'] != previous_options.get('report_id') and options['export_mode'] != 'print':
options['unreconciled'] = True
if options['export_mode'] == 'print':
# When printing the report, we don't want to include `no_followup` lines.
options['forced_domain'] = options.get('forced_domain', []) + [('no_followup', '=', False)]
options['columns'] = [col for col in options['columns'] if col['expression_label'] != 'no_followup']
if (not previous_options or not previous_options.get('account_type')):
for opt in options['account_type']:
if opt['id'] in ('trade_receivable', 'trade_payable'):
opt['selected'] = True
else:
opt['selected'] = False
def _custom_line_postprocessor(self, report, options, lines):
lines = super()._custom_line_postprocessor(report, options, lines)
# When exporting the Open Items Report to a specific customer, we don't want to display
# the Open Items Report line which only duplicates the customer's totals (redundant and confusing).
followup_report_line_id = report._get_line_from_xml_id(lines, 'account_reports.followup_report_line').id
single_partner_print = options.get('export_mode') == 'print' and len(options.get('selected_partner_ids', [])) == 1
if single_partner_print and followup_report_line_id:
index = next((i for i, line in enumerate(lines) if line.id == followup_report_line_id), None)
if index is not None:
lines.pop(index)
return lines
def _get_partner_ledger_query(self, options, date_scope, match_partner_on_partials=True):
query = super()._get_partner_ledger_query(options, date_scope, match_partner_on_partials=False)
query.add_where(SQL(
"(%s != 0 OR %s != 0)",
query.table.amount_residual,
query.table.amount_residual_currency,
))
return query
def _get_subformulas_rules(self):
subformula_rules = super()._get_subformulas_rules()
return subformula_rules | {
'amount': {'field': 'balance'}
}
def _get_date_order_clause(self, query, groupbys, date_from):
return [
SQL('%s ASC NULLS LAST', self._get_agg_expr('date_maturity', query, groupbys, date_from)),
*super()._get_date_order_clause(query, groupbys, date_from),
]
def action_send_follow_up(self, options):
template = self.env.ref('account_reports.email_template_customer_follow_up_report', False)
partners = self.env['res.partner'].browse(options.get('partner_ids', []))
return {
'name': self.env._("Send Reminder to %s", partners.name) if len(partners) == 1 else self.env._("Send Reminders"),
'type': 'ir.actions.act_window',
'views': [[False, 'form']],
'res_model': 'account.report.send',
'target': 'new',
'context': {
'default_mail_template_id': template.id,
'default_report_options': options,
},
}
def _get_partner_report_filename(self, report, partner, options):
today = fields.Date.context_today(report).strftime('%m%d%Y')
return f"{today}_Customer-Statement.pdf"

View File

@@ -0,0 +1,843 @@
import csv
import io
import json
from collections import defaultdict
from textwrap import shorten
from odoo import api, models, fields
from odoo.tools import float_repr, SQL
from odoo.exceptions import UserError
from odoo.addons.account_reports.utils.report_data_objects import AccountReportLineData, AccountReportLineChatterData
from odoo.addons.account_reports.models.account_report_snapshot import snapshotable_engine
def _keep_known_value(values):
""" Aggregator for the descriptive keys of an engine result row (account code, currency, dates, names, ...).
They describe the row's grouping key, so every partition containing that key reports the same value;
the most recent one is kept, falling back on the previous one when the row carries no value for it.
"""
return values[-1] if values[-1] is not None else values[0]
GL_RESULT_AGGREGATORS = {
'init_debit': sum,
'init_credit': sum,
'init_balance': sum,
'init_amount_currency': lambda v: sum(single_value for single_value in v if single_value is not None) if v is not None else 0.0,
'has_sublines': max,
# Descriptive keys added to the rows by _get_gl_engine_data, depending on the groupby
**dict.fromkeys(
(
'account_id', 'account_code', 'account_name', 'currency_id',
'date', 'invoice_date', 'line_name', 'move_name', 'partner_name',
),
_keep_known_value,
),
}
class AccountGeneralLedgerReportHandler(models.AbstractModel):
_name = 'account.general.ledger.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'General Ledger Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
options['buttons'].append({
'name': self.env._("CSV"),
'sequence': 50,
'action': 'export_file',
'action_param': 'generate_csv_export',
'file_export_type': self.env._('CSV'),
})
super()._custom_options_initializer(report, options, previous_options=previous_options)
# Remove multi-currency columns if needed
if self.env.user.has_group('base.group_multi_currency'):
options['multi_currency'] = True
else:
options['columns'] = [
column for column in options['columns']
if column['expression_label'] != 'amount_currency'
]
# Automatically unfold the report when printing it, unless some specific lines have been unfolded
options['unfold_all'] = (options['export_mode'] == 'print' and not options.get('unfolded_lines')) or options['unfold_all']
if options.get('force_not_unfold_all'):
options['unfold_all'] = False
options['custom_display_config'] = {
'templates': {
'AccountReportLineName': 'account_reports.GeneralLedgerLineName',
},
}
def _caret_options_initializer(self):
default_caret = self.env['account.report']._caret_options_initializer_default()
return {
**default_caret,
'id_with_accumulated_balance_caret': [
{'name': self.env._("View Journal Entry"), 'action': 'caret_option_open_record_form_custom_id_groupby', 'action_param': 'move_id'},
],
'undistributed_profits_losses': [
{'name': self.env._("Journal Items"), 'action': 'open_unallocated_items_journal_items'},
],
}
def open_unallocated_items_journal_items(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
return report.open_unallocated_items_journal_items(options, params)
@api.model
def open_journal_items(self, options, params):
params['view_ref'] = 'account_reports.view_move_line_account'
params['group_by_account'] = False
report = self.env['account.report'].browse(options['report_id'])
action = report.open_journal_items(options=options, params=params)
return action
def caret_option_open_record_form_custom_id_groupby(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
_model, aml_key = report._get_model_info_from_id(params['line_id'])
record_id = json.loads(aml_key)[1]
record = self.env['account.move.line'].browse(record_id)
target_record = record[params['action_param']] if 'action_param' in params else record
view_id = report._resolve_caret_option_view(target_record)
action = {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(view_id, 'form')], # view_id will be False in case the default view is needed
'res_model': target_record._name,
'res_id': target_record.id,
'context': self.env.context,
}
if view_id is not None:
action['view_id'] = view_id
return action
def _get_custom_groupby_map(self):
def custom_label_builder(grouping_keys):
"""
Batch label builder used to rename balance lines. The keys keep the order they are received in;
the engine already returned them in the order the report must display them.
"""
keys_names_in_sequence = {}
aml_id_by_key = {}
for key in grouping_keys:
if isinstance(key, str) and 'balance_line' in key:
keys_names_in_sequence[key] = self.env._("Initial Balance")
else:
keys_names_in_sequence[key] = key
aml_id_by_key[key] = json.loads(key)[1]
if aml_id_by_key:
display_name_by_aml_id = {
aml_vals['id']: aml_vals['display_name']
for aml_vals in self.env['account.move.line'].browse(aml_id_by_key.values()).read(['display_name'])
}
for key, aml_id in aml_id_by_key.items():
keys_names_in_sequence[key] = shorten(display_name_by_aml_id.get(aml_id) or '', width=200)
self.env['account.move'].invalidate_model()
return keys_names_in_sequence
def domain_builder(grouping_key):
if isinstance(grouping_key, str) and 'balance_line' in grouping_key:
return []
grouping_key_array = json.loads(grouping_key)
return [('id', '=', grouping_key_array[1]), ('date', '=', grouping_key_array[0])]
def pre_load_more_key_sort(x):
key = x[0]
return 0 if isinstance(key, str) and 'balance_line' in key else 1
return {
'id_with_accumulated_balance': {
'model': None,
'domain_builder': domain_builder,
'caret_builder': lambda grouping_key: None if isinstance(grouping_key, str) and 'balance_line' in grouping_key else 'id_with_accumulated_balance_caret',
'label_builder': custom_label_builder,
'pre_load_more_key_sort': pre_load_more_key_sort,
},
}
@snapshotable_engine(result_aggregators=GL_RESULT_AGGREGATORS, sub_engine_of='_report_engine_gl_initial_balance')
def _report_engine_gl_init_bal_sub(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
domain = [('account_id.include_initial_balance', '=', True)]
result = self._get_gl_engine_data(options, date_scope, formulas_dict, current_groupby, additional_domain=domain, warnings=warnings)
return result
def _report_engine_gl_initial_balance(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
init_balance = self._report_engine_gl_init_bal_sub(options, date_scope, formulas_dict, current_groupby, warnings=warnings)
date_from = fields.Date.from_string(options['date']['date_from'])
current_fiscalyear_date_from = self.env.company.compute_fiscalyear_dates(date_from)['date_from']
if current_fiscalyear_date_from <= date_from:
pl_domain = [
('account_id.include_initial_balance', '=', False),
('date', '>=', fields.Date.to_string(current_fiscalyear_date_from)),
]
pl_init_balance = self._get_gl_engine_data(options, date_scope, formulas_dict, current_groupby, additional_domain=pl_domain, warnings=warnings)
else:
pl_init_balance = None
if not pl_init_balance:
return init_balance
exprs = next(iter(formulas_dict.values()))
if not current_groupby:
res_dict = dict(init_balance[exprs])
for k, v in pl_init_balance[exprs].items():
res_dict[k] = GL_RESULT_AGGREGATORS.get(k, _keep_known_value)((res_dict.get(k), v))
return {exprs: res_dict}
merged_dict = {}
for partition in [init_balance, pl_init_balance]:
if not partition:
continue
for key, row_dict in partition[exprs]:
if key not in merged_dict:
merged_dict[key] = dict(row_dict)
else:
for k, v in row_dict.items():
merged_dict[key][k] = GL_RESULT_AGGREGATORS.get(k, _keep_known_value)((merged_dict[key].get(k), v))
return {exprs: list(merged_dict.items())}
def _report_engine_general_ledger(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._get_gl_engine_data(options, date_scope, formulas_dict, current_groupby, warnings=warnings)
def _get_gl_engine_data(self, options, date_scope, formulas_dict, current_groupby, additional_domain=None, warnings=None):
def get_grouping_key(row, groupby):
if groupby == 'id_with_accumulated_balance':
if not row['id']:
return f"balance_line_{row['account_id']}"
else:
return json.dumps([fields.Date.to_string(row['date']), row['id']])
return row[groupby] if groupby else None
query = self._get_query(options, date_scope, current_groupby, additional_domain=additional_domain)
currency_id = self.env.company.currency_id.id
subformulas = set()
for exprs in formulas_dict.values():
for expr in exprs:
if expr.subformula:
subformulas.add(expr.subformula)
line_dict_template = {
'has_sublines': False,
}
for sub in subformulas:
if sub.endswith(('debit', 'credit', 'balance')):
line_dict_template[sub] = 0.0
else:
line_dict_template[sub] = None
rows_by_key = {}
for row in self.env.execute_query_dict(query):
aml_key = get_grouping_key(row, current_groupby)
is_balance_line = isinstance(aml_key, str) and 'balance_line' in aml_key
if aml_key not in rows_by_key:
line_dict = line_dict_template.copy()
line_dict['has_sublines'] = True
if current_groupby == 'id_with_accumulated_balance':
line_dict['account_id'] = row.get('account_id') # Needed for batching
if not is_balance_line:
line_dict['date'] = row.get('date')
line_dict['partner_name'] = row.get('partner_name')
line_dict['line_name'] = row.get('line_name')
line_dict['account_code'] = row.get('account_code')
line_dict['account_name'] = row.get('account_name')
line_dict['move_name'] = row.get('move_name')
if any(column['expression_label'] == 'invoice_date' for column in options['columns']):
line_dict['invoice_date'] = row.get('invoice_date')
if row.get('currency_id') and row['currency_id'] != currency_id:
line_dict['currency_id'] = row['currency_id']
elif current_groupby == 'account_id':
line_dict['account_code'] = row.get('account_code')
if row.get('currency_id'):
line_dict['currency_id'] = row['currency_id']
rows_by_key[aml_key] = line_dict
else:
line_dict = rows_by_key[aml_key]
for sub in subformulas:
if is_balance_line and sub.startswith('period_'):
continue
if sub.endswith('debit'):
line_dict[sub] = (line_dict.get(sub) or 0.0) + (row.get('debit', 0.0) or 0.0)
elif sub.endswith('credit'):
line_dict[sub] = (line_dict.get(sub) or 0.0) + (row.get('credit', 0.0) or 0.0)
elif sub.endswith('balance'):
line_dict[sub] = (line_dict.get(sub) or 0.0) + (row.get('balance', 0.0) or 0.0)
elif sub.endswith('amount_currency'):
line_curr = row.get('currency_id')
if line_curr and line_curr != currency_id and row.get('amount_currency') is not None:
current_val = line_dict.get(sub)
if current_val is None:
current_val = 0.0
line_dict[sub] = current_val + row['amount_currency']
else:
if sub not in line_dict or line_dict[sub] is None:
line_dict[sub] = row.get(sub)
if not current_groupby:
return {next(iter(formulas_dict.values())): rows_by_key.get(None, line_dict_template)} # None is the key for total line as there is no groupby
return {next(iter(formulas_dict.values())): list(rows_by_key.items())}
def _get_query(self, options, date_scope, current_groupby, order_by_account=False, additional_domain=None):
report = self.env['account.report'].browse(options['report_id'])
options_date_from = fields.Date.from_string(options['date']['date_from'])
current_fiscalyear_date_from = self.env.company.compute_fiscalyear_dates(options_date_from)['date_from']
# We want to exclude move lines from expense and income accounts before the fiscal year for every groupby under account_id
if additional_domain is None:
additional_domain = [
'|',
('account_id.include_initial_balance', '=', True),
('date', '>=', current_fiscalyear_date_from),
]
report_query = report._get_report_query(options, date_scope, additional_domain)
if options.get('export_mode') == 'print' and options.get('filter_search_bar') and current_groupby not in ('id_with_accumulated_balance', 'id'):
search_bar_sql = SQL(
"""
AND account_move_line.account_id = ANY(%(search_bar_account_query)s)
""",
search_bar_account_query=self.env['account.account']._search([
'|',
('display_name', 'ilike', options.get('filter_search_bar')),
('code', 'like', options.get('filter_search_bar')),
*self.env['account.account']._check_company_domain(self.env['account.report'].get_report_company_ids(options)),
]).subselect()
)
else:
search_bar_sql = SQL()
additional_select = SQL("")
joins = SQL("")
groupby = []
if current_groupby == 'id_with_accumulated_balance':
account_code_select = self.env['account.account']._field_to_sql('account_move_line__account_id', 'code', report_query)
account_name_select = self.env['account.account']._field_to_sql('account_move_line__account_id', 'name')
invoice_date_select = SQL(
"""
MIN(
CASE
WHEN account_move_line.date >= %(date)s THEN account_move_line.invoice_date
ELSE NULL
END
) AS invoice_date,
""",
date=options_date_from,
) if any(column['expression_label'] == 'invoice_date' for column in options['columns']) else SQL("")
additional_select = SQL("""
CASE
WHEN account_move_line.date >= %(date)s THEN account_move_line.id
ELSE NULL
END AS id,
CASE
WHEN account_move_line.date >= %(date)s THEN account_move_line.date
ELSE NULL
END AS date,
%(invoice_date_select)s
MIN(move.name) AS move_name,
CASE
WHEN MIN(account_move_line.currency_id) = MAX(account_move_line.currency_id)
THEN SUM(account_move_line.amount_currency)
ELSE NULL
END AS amount_currency,
MIN(partner.name) AS partner_name,
CASE
WHEN MIN(account_move_line.currency_id) = MAX(account_move_line.currency_id)
THEN MIN(account_move_line.currency_id)
ELSE NULL
END AS currency_id,
MIN(account_move_line__account_id.id) AS account_id,
MIN(account_move_line.name) AS line_name,
MIN(%(account_name_select)s) AS account_name,
MIN(%(account_code_select)s) AS account_code,
""",
date=options_date_from,
invoice_date_select=invoice_date_select,
account_name_select=account_name_select,
account_code_select=account_code_select,
)
joins = SQL("""
LEFT JOIN res_partner partner ON partner.id = account_move_line.partner_id
JOIN account_move move ON move.id = account_move_line.move_id
""")
groupby = [SQL("1"), SQL("2"), SQL("account_move_line.account_id")]
elif current_groupby == 'account_id':
additional_select = SQL("""
account_move_line__account_id.id AS account_id,
account_move_line__account_id.account_type AS account_type,
SUM(account_move_line.amount_currency) AS amount_currency,
account_move_line__account_id.currency_id AS currency_id,
""")
groupby = [SQL("account_move_line__account_id.id"), SQL("account_move_line__account_id.currency_id")]
elif current_groupby:
groupby_field_sql = self.env['account.move.line']._field_to_sql('account_move_line', current_groupby, report_query)
additional_select = SQL("%s AS %s,", groupby_field_sql, SQL.identifier(current_groupby))
groupby = [groupby_field_sql]
account_table = report_query.table._join('account_id')
if current_groupby == 'account_id' or order_by_account:
order_clause = [self.env['account.account']._order_to_sql(account_table, False)]
groupby = order_clause + groupby
else:
order_clause = []
if current_groupby == 'id_with_accumulated_balance':
order_clause.append(SQL("2 NULLS FIRST, move_name, 1 NULLS FIRST"))
return SQL(
"""
SELECT
%(additional_select)s
COALESCE(SUM(%(select_debit)s), 0.0) AS debit,
COALESCE(SUM(%(select_credit)s), 0.0) AS credit,
COALESCE(SUM(%(select_balance)s), 0.0) AS balance
FROM %(from_clause)s
%(joins)s
WHERE %(where_clause)s
%(search_bar_sql)s
%(additional_groupby)s
%(orderby_clause)s
""",
additional_select=additional_select,
select_balance=report_query.table.consolidation_balance,
select_debit=report_query.table.consolidation_debit,
select_credit=report_query.table.consolidation_credit,
from_clause=report_query.from_clause,
joins=joins,
where_clause=report_query.where_clause,
search_bar_sql=search_bar_sql,
additional_groupby=SQL("GROUP BY %s", SQL(",").join(groupby)) if groupby else SQL(),
orderby_clause=SQL("ORDER BY %s", SQL(",").join(order_clause)) if order_clause else SQL(),
)
def _report_expand_unfoldable_line_with_groupby(self, line_dict_id, groupby, options, unfold_all_batch_data=None, limit_to_load=None):
"""
Shadows the function from account_report, in order to compute accumulated balances.
"""
if limit_to_load and groupby.replace(' ', '').split(',')[0] == 'account_id':
# Done for usability. We don't apply any load more limit for that grouping, assuming the number of accounts will always be small enough
limit_to_load = None
report = self.env['account.report'].browse(options['report_id'])
expansion_result_lines = report._report_expand_unfoldable_line_with_groupby(line_dict_id, groupby, options, unfold_all_batch_data=unfold_all_batch_data, limit_to_load=limit_to_load)
if groupby != 'id_with_accumulated_balance':
return expansion_result_lines
colname_to_idx = defaultdict(dict)
for idx, col in enumerate(options.get('columns', [])):
colname_to_idx[col['column_group_index']][col['expression_label']] = idx
initial_balance_line_ids = set()
for line in expansion_result_lines:
_markup, _model, grouping_key = report._parse_line_id(line.id)[-1]
if isinstance(grouping_key, str) and grouping_key.startswith('balance_line_'):
initial_balance_line_ids.add(line.id)
col_group_indexes = range(len(options['column_groups']))
accumulated_balance_by_colgroup = {
col_group_index: 0.0
for col_group_index in col_group_indexes
}
for col_group_index in col_group_indexes:
if 'balance' not in colname_to_idx[col_group_index]:
continue
for line in expansion_result_lines:
line_balance = line.columns[colname_to_idx[col_group_index]['balance']].no_format or 0
accumulated_balance_by_colgroup[col_group_index] += line_balance
if line.id not in initial_balance_line_ids:
new_col_data = report._build_column_data(accumulated_balance_by_colgroup[col_group_index], options['columns'][colname_to_idx[col_group_index]['balance']], options)
line.columns[colname_to_idx[col_group_index]['balance']] = new_col_data
return expansion_result_lines
def _get_fiscalyear_start_date(self, options):
options_date_from = fields.Date.to_date(options['date']['date_from'])
return self.env.company.compute_fiscalyear_dates(options_date_from)['date_from']
def _adjust_total_with_additional_lines(self, total_line_columns, additional_lines_values):
for line_values in additional_lines_values:
for col in total_line_columns:
if col and col.expression_label in line_values:
if col.no_format is not None:
col.no_format += line_values[col.expression_label]
else:
col.no_format = line_values[col.expression_label]
col.is_zero = not bool(col.no_format)
return total_line_columns
def _fix_init_balance_amount_currency_column(self, report, options, lines):
""" Fix the currency on the amount_currency column to align with the account currency
"""
amount_currency_indexes = [
index for index, column in enumerate(options['columns'])
if column['expression_label'] == 'amount_currency'
]
if not amount_currency_indexes:
return
def parse_groupby_line(line):
markup, model, value = report._parse_line_id(line.id)[-1]
return (markup['groupby'] if isinstance(markup, dict) else None), model, value
account_ids = {
value
for groupby, model, value in map(parse_groupby_line, lines)
if groupby == 'account_id' and model == 'account.account'
}
currency_by_account_id = {
account.id: account.currency_id
for account in self.env['account.account'].browse(account_ids)
if account.currency_id
}
for line in lines:
current_account_id = report._get_res_id_from_line_id(line.id, 'account.account')
current_currency = currency_by_account_id.get(current_account_id)
if current_currency:
for index in amount_currency_indexes:
column = line.columns[index]
line.columns[index] = report._build_column_data(
column.no_format,
options['columns'][index],
options,
currency=current_currency,
)
def _custom_line_postprocessor(self, report, options, lines):
general_ledger_custom_engine_line = self.env.ref('account_reports.general_ledger_custom_engine_line')
processed_lines = []
main_line_dict = None
account_move_lines = []
unaffected_earning_values = defaultdict(float)
cta_values = defaultdict(float)
if report._parse_line_id(lines[0].id)[-1] == ('', 'account.report.line', report.line_ids[0].id):
unaffected_earning_lines = report._get_unallocated_earnings_lines(options, 'from_beginning')
else:
unaffected_earning_lines = []
if report.currency_translation == 'cta' and report._parse_line_id(lines[0].id)[-1] == ('', 'account.report.line', report.line_ids[0].id):
cta_line = report._compute_cumulative_translation_adjustment_lines(options, 'from_beginning')
cumulative_translation_adjustment_lines = [cta_line] if cta_line else []
else:
cumulative_translation_adjustment_lines = []
self._fix_init_balance_amount_currency_column(report, options, lines)
for line in lines + unaffected_earning_lines + cumulative_translation_adjustment_lines:
for column in line.columns:
if column.expression_label == 'amount_currency' and column.is_zero:
column.no_format = None
markup, model, res_id = report._parse_line_id(line.id)[-1]
if model == 'account.report.line' and res_id == general_ledger_custom_engine_line.id:
main_line_dict = line
elif markup in ('undistributed_profits_losses', 'unallocated_earnings'):
for column in line.columns:
if column.figure_type == 'monetary':
unaffected_earning_values[column.expression_label] += column.no_format or 0.0
elif markup == 'cumulative_translation_adjustment':
for column in line.columns:
if column.figure_type == 'monetary':
cta_values[column.expression_label] += column.no_format or 0.0
else:
processed_lines.append(line)
if (
model is None and markup == {'groupby': 'id_with_accumulated_balance'}
and not (isinstance(res_id, str) and res_id.startswith('balance_line_')) and options.get('export_mode') != 'file'
):
line.chatter = AccountReportLineChatterData(id=json.loads(res_id)[1])
account_move_lines.append(line)
if account_move_lines:
line_ids = (l.chatter.id for l in account_move_lines)
account_moves = {
line['id']: line['move_id']
for line in self.env['account.move.line'].browse(line_ids).read(['id', 'move_id'], load=False)
}
for line in account_move_lines:
line.chatter.id = account_moves.get(line.chatter.id)
line.chatter.model = 'account.move'
if self.env.company.totals_below_sections and not options.get('ignore_totals_below_sections'):
if unaffected_earning_lines:
total_line = processed_lines.pop(-1)
total_line.columns = self._adjust_total_with_additional_lines(total_line.columns, [unaffected_earning_values])
processed_lines.extend(unaffected_earning_lines)
processed_lines.append(total_line)
if cumulative_translation_adjustment_lines and not all(col.is_zero for col in cumulative_translation_adjustment_lines[0].columns):
total_line = processed_lines.pop(-1)
total_line.columns = self._adjust_total_with_additional_lines(total_line.columns, [cta_values])
processed_lines.extend(cumulative_translation_adjustment_lines)
processed_lines.append(total_line)
else:
processed_lines.extend(unaffected_earning_lines)
if cumulative_translation_adjustment_lines and not all(col.is_zero for col in cumulative_translation_adjustment_lines[0].columns):
processed_lines.extend(cumulative_translation_adjustment_lines)
if main_line_dict:
processed_lines.append(
AccountReportLineData(
id=report._get_generic_line_id(None, None, 'total'),
name=self.env._("Total General Ledger"),
columns=self._adjust_total_with_additional_lines(main_line_dict.columns, [unaffected_earning_values, cta_values]),
level=1,
)
)
return processed_lines
def _custom_unfold_all_batch_data_generator(self, report, options, lines_to_expand_by_function):
""" Generate the custom engine's results for each full-sub-groupby-key that
would be created when doing an unfold-all on the report.
"""
def build_full_sub_groupby_key(report_line_id, full_sub_groupby_key_elements, current_groupby):
return f"[{report_line_id}]{','.join(full_sub_groupby_key_elements)}=>{current_groupby}"
results = {}
column_groups_options = report._split_options_per_column_group(options)
for line_to_expand in lines_to_expand_by_function.get('_report_expand_unfoldable_line_with_groupby', []):
report_line_id = report._get_res_id_from_line_id(line_to_expand.id, 'account.report.line')
report_line = self.env['account.report.line'].browse(report_line_id)
groupby_list = [groupby.strip() for groupby in (report_line._get_groupby(options) or '').split(',')]
if groupby_list != ['account_id', 'id_with_accumulated_balance']:
continue
grouped_formulas = report._group_expression_formulas(options, report_line.expression_ids)
# The custom engines are computed first; the aggregations below are expressed in terms of their results.
for engine_name in ('_report_engine_gl_initial_balance', '_report_engine_general_ledger'):
for (date_scope, _formulas_groupby), formulas_dict in grouped_formulas.get(engine_name, {}).items():
for column_group_index, column_group_options in column_groups_options.items():
for current_groupby in groupby_list:
engine_res = report._get_custom_report_function(engine_name, 'engine')(column_group_options, date_scope, formulas_dict, current_groupby)
for expressions, formula_res in engine_res.items():
if current_groupby == 'account_id':
rows_by_full_sub_groupby_key = {build_full_sub_groupby_key(report_line_id, [], current_groupby): formula_res}
else: # id_with_accumulated_balance: the results are split per account, each account being expanded on its own
rows_by_full_sub_groupby_key = defaultdict(list)
for grouping_key, row_res in formula_res:
full_sub_groupby_key = build_full_sub_groupby_key(report_line_id, [f"account_id:{row_res['account_id']}"], current_groupby)
rows_by_full_sub_groupby_key[full_sub_groupby_key].append((grouping_key, row_res))
for full_sub_groupby_key, rows in rows_by_full_sub_groupby_key.items():
groupby_expression_totals = results.setdefault(full_sub_groupby_key, {}).setdefault(column_group_index, {})
for expression in expressions:
groupby_expression_totals[expression] = {
'value': [(grouping_key, row_res.get(expression.subformula)) for grouping_key, row_res in rows],
'sublines_info': {grouping_key for grouping_key, row_res in rows if row_res.get('has_sublines')},
}
custom_expressions = report_line.expression_ids.filtered(lambda expr: expr.engine == 'custom')
# Aggregations are computed last, once every expression they reference is available in results.
for current_groupby in groupby_list:
# The aggregations are evaluated for the groupby currently being expanded, not for the one grouped_formulas
# was built with (it is always None here, since nothing is expanded yet when this generator runs).
aggregations_with_date_scope = []
for (date_scope, _formulas_groupby), formulas_dict in grouped_formulas.get('aggregation', {}).items():
for expressions in formulas_dict.values():
for expression in expressions:
aggregations_with_date_scope.append((date_scope, current_groupby, expression))
if not aggregations_with_date_scope:
continue
key_suffix = f'=>{current_groupby}'
for full_sub_groupby_key, column_groups_results in results.items():
if not full_sub_groupby_key.startswith(f'[{report_line_id}]') or not full_sub_groupby_key.endswith(key_suffix):
continue
for column_group_index, column_group_options in column_groups_options.items():
groupby_expression_totals = column_groups_results.setdefault(column_group_index, {})
# Some groupby might not have results in both engines. So we manually have to provide default values to allow aggregations
for expression in custom_expressions:
groupby_expression_totals.setdefault(expression, {'value': [], 'sublines_info': set()})
aggregation_formula_result = report._compute_totals_no_batch_aggregation(column_group_options, aggregations_with_date_scope, groupby_expression_totals, {})
# Partially taken from inject_formula_results
for expressions, result in aggregation_formula_result.items():
expression_value = []
sublines_info = set()
for grouping_key, result_dict in result:
if result_dict['has_sublines']:
sublines_info.add(grouping_key)
expression_value.append((grouping_key, result_dict['result']))
for expression in expressions:
groupby_expression_totals[expression] = {
'value': expression_value,
'sublines_info': sublines_info,
}
return results
def generate_csv_export(self, options):
if len(options['column_groups']) > 1:
raise UserError(self.env._("CSV export only works with one column group"))
report = self.env['account.report'].browse(options['report_id'])
return {
'file_content': self._generate_csv_lazy_export(options),
'file_type': 'csv',
'file_name': report.get_default_report_filename(options, 'csv')
}
def _generate_csv_lazy_export(self, options):
with self.pool.cursor() as new_cr:
self.env.flush_all()
handler = self.with_env(self.env(cr=new_cr))
cur_data = {
currency.id: {'name': currency.name, 'decimal_places': currency.decimal_places}
for currency in handler.env['res.currency'].with_context(active_test=False).search([])
}
company_currency_id = handler.env.company.currency_id.id
def csv_format_account_line(account_line, has_code=True):
if has_code:
cells = list(handler.env['account.account']._split_code_name(account_line.name))
else:
cells = ['/', account_line.name]
for col in account_line.columns:
cell = col.name
currency_id = col.currency.id if col.currency else company_currency_id
# The aggregation engine may return an int (e.g. 0) for a monetary value, so bool aside, any number is formatted.
if col.figure_type == 'monetary' and isinstance(cell, (int, float)) and not isinstance(cell, bool):
cell = float_repr(float(cell), cur_data[currency_id]['decimal_places'])
if col.expression_label == 'amount_currency':
cells.append(cell)
cell = cur_data[currency_id]['name'] if currency_id != company_currency_id else ''
cells.append(cell)
return csv_format(cells)
def csv_format_aml_res(aml_res):
cells = ['', aml_res.get('move_name', '')]
for col in options['columns']:
cell = aml_res.get(col['expression_label'], '')
if col['figure_type'] == 'monetary':
if col['expression_label'] == 'amount_currency':
currency_id = aml_res['currency_id']
amount_cur_cell = float_repr(cell, cur_data[currency_id]['decimal_places']) if currency_id != company_currency_id else ''
cells.append(amount_cur_cell)
cell = cur_data[currency_id]['name'] if currency_id != company_currency_id else ''
else:
cell = float_repr(cell, cur_data[company_currency_id]['decimal_places'])
cells.append(cell)
return csv_format(cells)
def csv_format(cells):
with io.StringIO() as buf:
writer = csv.writer(buf, delimiter=',', lineterminator='\n')
writer.writerow(cells)
return buf.getvalue().encode()
col_names = [col['name'] for col in options['columns']]
currency_idx = next((i for i, col in enumerate(options['columns']) if col.get('expression_label') == 'amount_currency'), None)
header = [handler.env._("Code"), handler.env._("Name")]
if currency_idx is not None:
header += [
*col_names[:currency_idx],
handler.env._("Amount Currency"),
handler.env._("Currency"),
*col_names[currency_idx + 1:]
]
else:
header += col_names
yield csv_format(header)
report = handler.env['account.report'].browse(options['report_id'])
agg_lines_options = report.get_options(previous_options={**options, 'unfolded_lines': [], 'force_not_unfold_all': True})
agg_lines = report.with_context(no_format=True)._get_lines(agg_lines_options)
# Exclude total lines
account_lines = []
accounts = []
for agg_line in agg_lines:
line_id = agg_line.id
markup, model, res_id = report._parse_line_id(line_id)[-1]
if markup != 'total':
if model == 'account.account':
accounts.append(res_id)
account_lines.append(agg_line)
if not account_lines:
return
accounts_with_codes = {account.id for account in handler.env['account.account'].browse(accounts) if account.code}
account_lines_iter = iter(account_lines)
account_line = next(account_lines_iter)
_model, account_id = report._get_model_info_from_id(account_line.id)
yield csv_format_account_line(account_line, has_code=account_id in accounts_with_codes)
aml_query = handler._get_query(options, 'from_beginning', 'id_with_accumulated_balance', order_by_account=True)
handler.env.cr.execute(SQL("%s", aml_query))
progress = 0
while aml_line := handler.env.cr.dictfetchone():
while account_id != aml_line['account_id']:
account_line = next(account_lines_iter)
_model, account_id = report._get_model_info_from_id(account_line.id)
yield csv_format_account_line(account_line, has_code=account_id in accounts_with_codes)
progress = 0
if aml_line['id'] is None:
aml_line['move_name'] = handler.env._("Initial Balance")
aml_line['partner_name'] = ''
progress = aml_line['balance'] = (progress + aml_line['balance'])
yield csv_format_aml_res(aml_line)
# These are the "Result Brought Forward" lines
for account_line in account_lines_iter:
yield csv_format_account_line(account_line, has_code=False)
total_line = agg_lines[-1]
yield csv_format_account_line(total_line)

View File

@@ -0,0 +1,692 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from odoo import models, api, _
from odoo.exceptions import UserError
from odoo.fields import Domain
from odoo.tools import SQL
from odoo.addons.account_reports.utils.report_data_objects import AccountReportLineData
class AccountTaxReportHandler(models.AbstractModel):
_name = 'account.tax.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Account Report Handler for Tax Reports'
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
if 'account_reports.common_warning_draft_in_period' in warnings:
# Recompute the warning 'common_warning_draft_in_period' to not include tax closing entries in the banner of unposted moves
if not self.env['account.move'].search_count(
[('state', '=', 'draft'), ('date', '<=', options['date']['date_to']),
('closing_return_id', '=', False)],
limit=1,
):
warnings.pop('account_reports.common_warning_draft_in_period')
# -------------------------------------------------------------------------
# TAX CLOSING
# -------------------------------------------------------------------------
def _get_amls_with_archived_tags_domain(self, options):
domain = [
('tax_tag_ids.active', '=', False),
('parent_state', '=', 'posted'),
('date', '>=', options['date']['date_from']),
]
if options['date']['mode'] == 'single':
domain.append(('date', '<=', options['date']['date_to']))
return domain
def action_open_amls_with_archived_tags(self, options, params=None):
return {
'name': _("Journal items with archived tax tags"),
'type': 'ir.actions.act_window',
'res_model': 'account.move.line',
'domain': self._get_amls_with_archived_tags_domain(options),
'context': {'active_test': False},
'views': [(self.env.ref('account_reports.view_archived_tag_move_tree').id, 'list')],
}
class AccountGenericTaxReportHandler(models.AbstractModel):
_name = 'account.generic.tax.report.handler'
_inherit = ['account.tax.report.handler']
_description = 'Generic Tax Report Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options)
options['custom_display_config'] = {
'css_custom_class': 'generic_tax_report',
'templates': {
'AccountReportLineName': 'account_reports.TaxReportLineName',
},
}
def _dynamic_lines_generator(self, report, options, all_column_groups_expression_totals, warnings=None):
return self._get_dynamic_lines(report, options, 'default', warnings)
def _caret_options_initializer(self):
return {
'generic_tax_report': [
{'name': _("Audit"), 'action': 'caret_option_audit_tax'},
]
}
def _get_dynamic_lines(self, report, options, grouping, warnings=None):
""" Compute the report lines for the generic tax report.
:param options: The report options.
:return: A list of lines, each one being a python dictionary.
"""
options_by_column_group = report._split_options_per_column_group(options)
# Compute tax_base_amount / tax_amount for each selected groupby.
if grouping == 'tax_account':
groupby_fields = [('src_tax', 'type_tax_use'), ('src_tax', 'id'), ('account', 'id')]
comodels = [None, 'account.tax', 'account.account']
elif grouping == 'account_tax':
groupby_fields = [('src_tax', 'type_tax_use'), ('account', 'id'), ('src_tax', 'id')]
comodels = [None, 'account.account', 'account.tax']
else:
groupby_fields = [('src_tax', 'type_tax_use'), ('src_tax', 'id')]
comodels = [None, 'account.tax']
if grouping in ('tax_account', 'account_tax'):
tax_amount_hierarchy = self._read_generic_tax_report_amounts(report, options_by_column_group, groupby_fields)
else:
tax_amount_hierarchy = self._read_generic_tax_report_amounts_no_tax_details(report, options, options_by_column_group)
# Fetch involved records in order to ensure all lines are sorted according the comodel order.
# To do so, we compute 'sorting_map_list' allowing to retrieve each record by id and the order
# to be used.
record_ids_gb = [set() for dummy in groupby_fields]
def populate_record_ids_gb_recursively(node, level=0):
for k, v in node.items():
if k:
record_ids_gb[level].add(k)
if v.get('children'):
populate_record_ids_gb_recursively(v['children'], level=level + 1)
populate_record_ids_gb_recursively(tax_amount_hierarchy)
sorting_map_list = []
for i, comodel in enumerate(comodels):
if comodel:
# Relational records.
records = self.env[comodel].with_context(active_test=False).search([('id', 'in', tuple(record_ids_gb[i]))])
sorting_map = {r.id: (r, j) for j, r in enumerate(records)}
sorting_map_list.append(sorting_map)
else:
# src_tax_type_tax_use.
selection = self.env['account.tax']._fields['type_tax_use']._description_selection(self.env)
sorting_map_list.append({v[0]: (v, j) for j, v in enumerate(selection) if v[0] in record_ids_gb[i]})
# Compute report lines.
lines = []
self._populate_lines_recursively(
report,
options,
lines,
sorting_map_list,
groupby_fields,
tax_amount_hierarchy,
warnings=warnings,
)
return lines
# -------------------------------------------------------------------------
# GENERIC TAX REPORT COMPUTATION (DYNAMIC LINES)
# -------------------------------------------------------------------------
@api.model
def _read_generic_tax_report_amounts_no_tax_details(self, report, options, options_by_column_group):
# Fetch the group of taxes.
# If all child taxes have a 'none' type_tax_use, all amounts are aggregated and only the group appears on the report.
company_ids = report.get_report_company_ids(options)
company_domain = self.env['account.tax']._check_company_domain(company_ids)
company_where_query = self.env['account.tax'].with_context(active_test=False)._search(company_domain, bypass_access=True)
self.env.cr.execute(SQL(
'''
SELECT
account_tax.id,
account_tax.type_tax_use,
ARRAY_AGG(child_tax.id ORDER BY child_tax.id) AS child_tax_ids,
ARRAY_AGG(child_tax.type_tax_use ORDER BY child_tax.id) AS child_types,
ARRAY_AGG(child_tax.tax_exigibility ORDER BY child_tax.id) as child_exigibility
FROM account_tax_filiation_rel account_tax_rel
JOIN account_tax ON account_tax.id = account_tax_rel.parent_tax
JOIN account_tax child_tax ON child_tax.id = account_tax_rel.child_tax
WHERE account_tax.amount_type = 'group'
AND %s
GROUP BY account_tax.id
''', company_where_query.where_clause or SQL("TRUE")
))
group_of_taxes_info = {}
child_to_group_of_taxes = {}
for row in self.env.cr.dictfetchall():
row['to_expand'] = set(row['child_types']) != {'none'}
group_of_taxes_info[row['id']] = row
for child_id in row['child_tax_ids']:
child_to_group_of_taxes[child_id] = row['id']
results = defaultdict(lambda: { # key: type_tax_use
'base_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_non_deductible': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_deductible': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_due': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'children': defaultdict(lambda: { # key: tax_id
'base_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_non_deductible': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_deductible': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_due': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
}),
})
for column_group_index, options in options_by_column_group.items():
query = report._get_report_query(options, 'strict_range')
# make sure account_move is always joined
if 'account_move_line__move_id' not in query._joins:
query.table._sudo()._join('move_id', kind='JOIN')
# Fetch the base amounts.
self.env.cr.execute(SQL(
'''
SELECT
tax.id AS tax_id,
tax.type_tax_use AS tax_type_tax_use,
src_group_tax.id AS src_group_tax_id,
src_group_tax.type_tax_use AS src_group_tax_type_tax_use,
src_tax.id AS src_tax_id,
src_tax.type_tax_use AS src_tax_type_tax_use,
SUM(account_move_line.balance) AS base_amount
FROM %(table_references)s
JOIN account_move_line_account_tax_rel tax_rel ON account_move_line.id = tax_rel.account_move_line_id
JOIN account_tax tax ON tax.id = tax_rel.account_tax_id
LEFT JOIN account_tax src_tax ON src_tax.id = account_move_line.tax_line_id
LEFT JOIN account_tax src_group_tax ON src_group_tax.id = account_move_line.group_tax_id
WHERE %(search_condition)s
AND (
/* CABA */
account_move_line__move_id.always_tax_exigible
OR account_move_line__move_id.tax_cash_basis_rec_id IS NOT NULL
OR tax.tax_exigibility != 'on_payment'
)
AND (
(
/* Tax lines affecting the base of others. */
account_move_line.tax_line_id IS NOT NULL
AND (
src_tax.type_tax_use IN ('sale', 'purchase')
OR src_group_tax.type_tax_use IN ('sale', 'purchase')
)
)
OR
(
/* For regular base lines. */
account_move_line.tax_line_id IS NULL
AND tax.type_tax_use IN ('sale', 'purchase')
)
)
GROUP BY tax.id, src_group_tax.id, src_tax.id
ORDER BY src_group_tax.sequence, src_group_tax.id, src_tax.sequence, src_tax.id, tax.sequence, tax.id
''',
table_references=query.from_clause,
search_condition=query.where_clause,
))
group_of_taxes_with_extra_base_amount = set()
for row in self.env.cr.dictfetchall():
is_tax_line = bool(row['src_tax_id'])
if is_tax_line:
if row['src_group_tax_id'] \
and not group_of_taxes_info[row['src_group_tax_id']]['to_expand'] \
and row['tax_id'] in group_of_taxes_info[row['src_group_tax_id']]['child_tax_ids']:
# Suppose a base of 1000 with a group of taxes 20% affect + 10%.
# The base of the group of taxes must be 1000, not 1200 because the group of taxes is not
# expanded. So the tax lines affecting the base of its own group of taxes are ignored.
pass
elif row['tax_type_tax_use'] == 'none' and child_to_group_of_taxes.get(row['tax_id']):
# The tax line is affecting the base of a 'none' tax belonging to a group of taxes.
# In that case, the amount is accounted as an extra base for that group. However, we need to
# account it only once.
# For example, suppose a tax 10% affect base of subsequent followed by a group of taxes
# 20% + 30%. On a base of 1000.0, the tax line for 10% will affect the base of 20% + 30%.
# However, this extra base must be accounted only once since the base of the group of taxes
# must be 1100.0 and not 1200.0.
group_tax_id = child_to_group_of_taxes[row['tax_id']]
if group_tax_id not in group_of_taxes_with_extra_base_amount:
group_tax_info = group_of_taxes_info[group_tax_id]
results[group_tax_info['type_tax_use']]['children'][group_tax_id]['base_amount'][column_group_index] += row['base_amount']
group_of_taxes_with_extra_base_amount.add(group_tax_id)
else:
tax_type_tax_use = row['src_group_tax_type_tax_use'] or row['src_tax_type_tax_use']
results[tax_type_tax_use]['children'][row['tax_id']]['base_amount'][column_group_index] += row['base_amount']
else:
if row['tax_id'] in group_of_taxes_info and group_of_taxes_info[row['tax_id']]['to_expand']:
# Expand the group of taxes since it contains at least one tax with a type != 'none'.
group_info = group_of_taxes_info[row['tax_id']]
for child_tax_id, child_exigibility in zip(group_info['child_tax_ids'], group_info['child_exigibility']):
if child_exigibility != 'on_payment':
results[group_info['type_tax_use']]['children'][child_tax_id]['base_amount'][column_group_index] += row['base_amount']
else:
results[row['tax_type_tax_use']]['children'][row['tax_id']]['base_amount'][column_group_index] += row['base_amount']
# Fetch the tax amounts.
select_deductible = join_deductible = group_by_deductible = SQL()
if options.get('account_journal_report_tax_deductibility_columns'):
select_deductible = SQL(""", repartition.use_in_tax_closing AS trl_tax_closing
, SIGN(repartition.factor_percent) AS trl_factor""")
join_deductible = SQL("""JOIN account_tax_repartition_line repartition
ON account_move_line.tax_repartition_line_id = repartition.id""")
group_by_deductible = SQL(', repartition.use_in_tax_closing, SIGN(repartition.factor_percent)')
self.env.cr.execute(SQL(
'''
SELECT
tax.id AS tax_id,
tax.type_tax_use AS tax_type_tax_use,
group_tax.id AS group_tax_id,
group_tax.type_tax_use AS group_tax_type_tax_use,
SUM(account_move_line.balance) AS tax_amount
%(select_deductible)s
FROM %(table_references)s
JOIN account_tax tax ON tax.id = account_move_line.tax_line_id
%(join_deductible)s
LEFT JOIN account_tax group_tax ON group_tax.id = account_move_line.group_tax_id
WHERE %(search_condition)s
AND (
/* CABA */
account_move_line__move_id.always_tax_exigible
OR account_move_line__move_id.tax_cash_basis_rec_id IS NOT NULL
OR tax.tax_exigibility != 'on_payment'
)
AND (
(group_tax.id IS NULL AND tax.type_tax_use IN ('sale', 'purchase'))
OR
(group_tax.id IS NOT NULL AND group_tax.type_tax_use IN ('sale', 'purchase'))
)
GROUP BY tax.id, group_tax.id %(group_by_deductible)s
''',
select_deductible=select_deductible,
table_references=query.from_clause,
join_deductible=join_deductible,
search_condition=query.where_clause,
group_by_deductible=group_by_deductible,
))
for row in self.env.cr.dictfetchall():
# Manage group of taxes.
# In case the group of taxes is mixing multiple taxes having a type_tax_use != 'none', consider
# them instead of the group.
tax_id = row['tax_id']
if row['group_tax_id']:
tax_type_tax_use = row['group_tax_type_tax_use']
if row['group_tax_id'] not in group_of_taxes_info or not group_of_taxes_info[row['group_tax_id']]['to_expand']:
tax_id = row['group_tax_id']
else:
tax_type_tax_use = row['group_tax_type_tax_use'] or row['tax_type_tax_use']
results[tax_type_tax_use]['tax_amount'][column_group_index] += row['tax_amount']
results[tax_type_tax_use]['children'][tax_id]['tax_amount'][column_group_index] += row['tax_amount']
if options.get('account_journal_report_tax_deductibility_columns'):
tax_detail_label = False
if row['trl_factor'] > 0 and tax_type_tax_use == 'purchase':
tax_detail_label = 'tax_deductible' if row['trl_tax_closing'] else 'tax_non_deductible'
elif row['trl_tax_closing'] and (row['trl_factor'] > 0, tax_type_tax_use) in ((False, 'purchase'), (True, 'sale')):
tax_detail_label = 'tax_due'
if tax_detail_label:
results[tax_type_tax_use][tax_detail_label][column_group_index] += row['tax_amount'] * row['trl_factor']
results[tax_type_tax_use]['children'][tax_id][tax_detail_label][column_group_index] += row['tax_amount'] * row['trl_factor']
return results
def _read_generic_tax_report_amounts(self, report, options_by_column_group, groupby_fields):
""" Read the tax details to compute the tax amounts.
:param report:
:param options_by_column_group:
:param groupby_fields: A list of tuple (alias, field) representing the way the amounts must be grouped.
:return: A dictionary mapping each groupby key (e.g. a tax_id) to a sub dictionary containing:
base_amount: The tax base amount expressed in company's currency.
tax_amount The tax amount expressed in company's currency.
children: The children nodes following the same pattern as the current dictionary.
"""
fetch_group_of_taxes = False
select_clause_list = []
groupby_query_list = []
for alias, field in groupby_fields:
select_clause_list.append(SQL("%s AS %s", SQL.identifier(alias, field), SQL.identifier(f'{alias}_{field}')))
groupby_query_list.append(SQL.identifier(alias, field))
# Fetch both info from the originator tax and the child tax to manage the group of taxes.
if alias == 'src_tax':
select_clause_list.append(SQL("%s AS %s", SQL.identifier('tax', field), SQL.identifier(f'tax_{field}')))
groupby_query_list.append(SQL.identifier('tax', field))
fetch_group_of_taxes = True
# Fetch the group of taxes.
# If all children taxes are 'none', all amounts are aggregated and only the group will appear on the report.
# If some children taxes are not 'none', the children are displayed.
group_of_taxes_to_expand = set()
if fetch_group_of_taxes:
group_of_taxes = self.env['account.tax'].with_context(active_test=False).search([('amount_type', '=', 'group')])
for group in group_of_taxes:
if set(group.children_tax_ids.mapped('type_tax_use')) != {'none'}:
group_of_taxes_to_expand.add(group.id)
res = {}
for column_group_index, options in options_by_column_group.items():
query = report._get_report_query(options, 'strict_range')
tax_details_query = self.env['account.move.line']._get_query_tax_details(query)
# Avoid adding multiple times the same base amount sharing the same grouping_key.
# It could happen when dealing with group of taxes for example.
row_keys = set()
self.env.cr.execute(SQL(
'''
SELECT
%(select_clause)s,
trl.document_type = 'refund' AS is_refund,
SUM(CASE WHEN tdr.display_type = 'rounding' THEN 0 ELSE tdr.base_amount END) AS base_amount,
SUM(tdr.tax_amount) AS tax_amount
FROM (%(tax_details_query)s) AS tdr
JOIN account_tax_repartition_line trl ON trl.id = tdr.tax_repartition_line_id
JOIN account_tax tax ON tax.id = tdr.tax_id
JOIN account_tax src_tax ON
src_tax.id = COALESCE(tdr.group_tax_id, tdr.tax_id)
AND src_tax.type_tax_use IN ('sale', 'purchase')
JOIN account_account account ON account.id = tdr.base_account_id
WHERE tdr.tax_exigible
GROUP BY tdr.tax_repartition_line_id, trl.document_type, %(groupby_query)s
ORDER BY src_tax.sequence, src_tax.id, tax.sequence, tax.id
''',
select_clause=SQL(',').join(select_clause_list),
tax_details_query=tax_details_query,
groupby_query=SQL(',').join(groupby_query_list),
))
for row in self.env.cr.dictfetchall():
node = res
# tuple of values used to prevent adding multiple times the same base amount.
cumulated_row_key = [row['is_refund']]
for alias, field in groupby_fields:
grouping_key = f'{alias}_{field}'
# Manage group of taxes.
# In case the group of taxes is mixing multiple taxes having a type_tax_use != 'none', consider
# them instead of the group.
if grouping_key == 'src_tax_id' and row['src_tax_id'] in group_of_taxes_to_expand:
# Add the originator group to the grouping key, to make sure that its base amount is not
# treated twice, for hybrid cases where a tax is both used in a group and independently.
cumulated_row_key.append(row[grouping_key])
# Ensure the child tax is used instead of the group.
grouping_key = 'tax_id'
row_key = row[grouping_key]
cumulated_row_key.append(row_key)
cumulated_row_key_tuple = tuple(cumulated_row_key)
node.setdefault(row_key, {
'base_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'tax_amount': {column_group_index: 0.0 for column_group_index in range(len(options['column_groups']))},
'children': {},
})
sub_node = node[row_key]
# Add amounts.
if cumulated_row_key_tuple not in row_keys:
sub_node['base_amount'][column_group_index] += row['base_amount']
sub_node['tax_amount'][column_group_index] += row['tax_amount']
node = sub_node['children']
row_keys.add(cumulated_row_key_tuple)
return res
def _populate_lines_recursively(self, report, options, lines, sorting_map_list, groupby_fields, values_node, index=0, type_tax_use=None, parent_line_id=None, warnings=None):
''' Populate the list of report lines passed as parameter recursively. At this point, every amounts is already
fetched for every periods and every groupby.
:param options: The report options.
:param lines: The list of report lines to populate.
:param sorting_map_list: A list of dictionary mapping each encountered key with a weight to sort the results.
:param index: The index of the current element to process (also equals to the level into the hierarchy).
:param groupby_fields: A list of tuple <alias, field> defining in which way tax amounts should be grouped.
:param values_node: The node containing the amounts and children into the hierarchy.
:param type_tax_use: The type_tax_use of the tax.
:param parent_line_id: The line id of the parent line (if any)
:param warnings The warnings dictionnary.
'''
if index == len(groupby_fields):
return
alias, field = groupby_fields[index]
groupby_key = f'{alias}_{field}'
# Sort the keys in order to add the lines in the same order as the records.
sorting_map = sorting_map_list[index]
sorted_keys = sorted(list(values_node.keys()), key=lambda x: sorting_map[x][1])
for key in sorted_keys:
# Compute 'type_tax_use' with the first grouping since 'src_tax_type_tax_use' is always
# the first one.
if groupby_key == 'src_tax_type_tax_use':
type_tax_use = key
sign = -1 if type_tax_use == 'sale' else 1
# Prepare columns.
tax_amount_dict = values_node[key]
columns = []
tax_base_amounts = tax_amount_dict['base_amount']
tax_amounts = tax_amount_dict['tax_amount']
for column in options['columns']:
tax_base_amount = tax_base_amounts[column['column_group_index']]
tax_amount = tax_amounts[column['column_group_index']]
expr_label = column.get('expression_label')
col_value = ''
if expr_label == 'net' and index == len(groupby_fields) - 1:
col_value = sign * tax_base_amount
if expr_label == 'tax':
col_value = sign * tax_amount
columns.append(report._build_column_data(col_value, column, options=options))
# Add the non-deductible, deductible and due tax amounts.
if expr_label == 'tax' and options.get('account_journal_report_tax_deductibility_columns'):
for deduct_type in ('tax_non_deductible', 'tax_deductible', 'tax_due'):
columns.append(report._build_column_data(
sign * tax_amount_dict[deduct_type][column['column_group_index']],
{
'figure_type': 'monetary',
'column_group_index': column['column_group_index'],
'expression_label': deduct_type,
},
options=options,
))
report_line = self._build_report_line(report, options, columns, index if index == 0 else index + 1, groupby_key, sorting_map[key][0], parent_line_id, warnings)
if groupby_key == 'src_tax_id':
report_line.caret_options = 'generic_tax_report'
lines.append((0, report_line))
# Process children recursively.
self._populate_lines_recursively(
report,
options,
lines,
sorting_map_list,
groupby_fields,
tax_amount_dict.get('children'),
index=index + 1,
type_tax_use=type_tax_use,
parent_line_id=report_line.id,
warnings=warnings,
)
def _build_report_line(self, report, options, columns, level, groupby_key, value, parent_line_id, warnings=None):
""" Build the report line accordingly to its type.
:param options: The report options.
:param default_vals: The pre-computed report line values.
:param groupby_key: The grouping_key record.
:param value: The value that could be a record.
:param parent_line_id The line id of the parent line (if any, can be None otherwise)
:param warnings: The warnings dictionary.
:return: A python dictionary.
"""
base_line = AccountReportLineData(
columns=columns,
level=level,
unfoldable=False,
)
if parent_line_id is not None:
base_line.parent_id = parent_line_id
if groupby_key == 'src_tax_type_tax_use':
type_tax_use_option = value
base_line.id = report._get_generic_line_id(None, None, markup=type_tax_use_option[0], parent_line_id=parent_line_id)
base_line.name = type_tax_use_option[1]
elif groupby_key == 'src_tax_id':
tax = value
base_line.id = report._get_generic_line_id(tax._name, tax.id, parent_line_id=parent_line_id)
if tax.amount_type == 'percent':
base_line.name = f"{tax.name} ({tax.amount}%)"
if warnings is not None:
self._check_line_consistency(report, options, base_line, tax, warnings)
elif tax.amount_type == 'fixed':
base_line.name = f"{tax.name} ({tax.amount})"
else:
base_line.name = tax.name
if options.get('multi-company'):
base_line.name = f"{base_line.name} - {tax.company_id.display_name}"
elif groupby_key == 'account_id':
account = value
base_line.id = report._get_generic_line_id(account._name, account.id, parent_line_id=parent_line_id)
if options.get('multi-company'):
base_line.name = f"{account.display_name} - {account.company_id.display_name}"
else:
base_line.name = account.display_name
return base_line
def _check_line_consistency(self, report, options, report_line, tax, warnings=None):
tax_applied = tax.amount * sum(tax.invoice_repartition_line_ids.filtered(lambda tax_rep: tax_rep.repartition_type == 'tax').mapped('factor')) / 100
for column_group_index in report._split_options_per_column_group(options):
net_value = next((col.no_format for col in report_line.columns if col.column_group_index == column_group_index and col.expression_label == 'net'), 0)
tax_value = next((col.no_format for col in report_line.columns if col.column_group_index == column_group_index and col.expression_label == 'tax'), 0)
if net_value == '': # noqa: PLC1901
continue
currency = self.env.company.currency_id
computed_tax_amount = float(net_value or 0) * tax_applied
is_inconsistent = currency.compare_amounts(computed_tax_amount, tax_value)
if is_inconsistent:
error = abs((abs(tax_value) - abs(computed_tax_amount)) / float(net_value or 1))
# Error is bigger than 0.1%. We can not ignore it.
if error > 0.001:
report_line.get_custom()['alert'] = True # Custom here means that the line has an alert
warnings['account_reports.tax_report_warning_lines_consistency'] = {'alert_type': 'danger'}
return
# -------------------------------------------------------------------------
# BUTTONS & CARET OPTIONS
# -------------------------------------------------------------------------
def caret_option_audit_tax(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
model, tax_id = report._get_model_info_from_id(params['line_id'])
if model != 'account.tax':
raise UserError(_("Cannot audit tax from another model than account.tax."))
tax = self.env['account.tax'].browse(tax_id)
if tax.amount_type == 'group':
tax_affecting_base_domain = [
('tax_ids', 'in', tax.children_tax_ids.ids),
('tax_repartition_line_id', '!=', False),
]
else:
tax_affecting_base_domain = [
('tax_ids', '=', tax.id),
('tax_ids.type_tax_use', '=', tax.type_tax_use),
('tax_repartition_line_id', '!=', False),
]
domain = Domain(report._get_options_domain(options, 'strict_range')) & Domain.OR((
# Base lines
[
('tax_ids', 'in', tax.ids),
('tax_ids.type_tax_use', '=', tax.type_tax_use),
('tax_repartition_line_id', '=', False),
],
# Tax lines
[
('group_tax_id', '=', tax.id) if tax.amount_type == 'group' else ('tax_line_id', '=', tax.id),
],
# Tax lines acting as base lines
tax_affecting_base_domain,
))
ctx = self.env.context.copy()
ctx.update({'search_default_group_by_account': 2, 'expand': 1})
return {
'type': 'ir.actions.act_window',
'name': _('Journal Items for Tax Audit'),
'res_model': 'account.move.line',
'views': [[self.env.ref('account.view_move_line_tax_audit_tree').id, 'list']],
'domain': domain,
'context': ctx,
}
class AccountGenericTaxReportHandlerAccountTax(models.AbstractModel):
_name = 'account.generic.tax.report.handler.account.tax'
_inherit = ['account.generic.tax.report.handler']
_description = 'Generic Tax Report Custom Handler (Account -> Tax)'
def _dynamic_lines_generator(self, report, options, all_column_groups_expression_totals, warnings=None):
return super()._get_dynamic_lines(report, options, 'account_tax', warnings)
class AccountGenericTaxReportHandlerTaxAccount(models.AbstractModel):
_name = 'account.generic.tax.report.handler.tax.account'
_inherit = ['account.generic.tax.report.handler']
_description = 'Generic Tax Report Custom Handler (Tax -> Account)'
def _dynamic_lines_generator(self, report, options, all_column_groups_expression_totals, warnings=None):
return super()._get_dynamic_lines(report, options, 'tax_account', warnings)

View File

@@ -0,0 +1,24 @@
from odoo import api, models
class AccountJournal(models.Model):
_inherit = 'account.journal'
@api.model_create_multi
def create(self, vals_list):
journals = super().create(vals_list)
# Creating a journal might invalidate snapshots if journal groups are in use (the default group might need it, it will have to be in the options)
if self.env['account.journal.group'].search([], limit=1):
self.env.ref('account_reports.ir_cron_create_snapshots')._trigger()
return journals
def write(self, vals):
rslt = super().write(vals)
if 'journal_group_id' in vals:
# Might change the content of the default journal group ; snapshots need refresh
self.env.ref('account_reports.ir_cron_create_snapshots')._trigger()
return rslt

View File

@@ -0,0 +1,55 @@
from odoo import models, fields
import ast
class AccountJournal(models.Model):
_inherit = 'account.journal'
def _fill_general_dashboard_data(self, dashboard_data):
super()._fill_general_dashboard_data(dashboard_data)
for journal in self.filtered(lambda j: j.type == 'general'):
is_return_journal = journal == journal.company_id.account_tax_return_journal_id
dashboard_data[journal.id]['is_account_return_journal'] = is_return_journal
if not is_return_journal:
continue
closest_return = self.env['account.return'].search_read(
domain=[
*self.env['account.return']._check_company_domain(journal.company_id),
('type_id.category', '=', 'account_return'),
('is_completed', '=', False), # Use = False for clearer intent
],
fields=['date_deadline'],
limit=1,
order='date_deadline ASC',
)
if not closest_return:
color = 'primary' # invite the user to generate the returns by setting the account opening date
else:
deadline = closest_return[0]['date_deadline']
today = fields.Date.context_today(self)
if deadline < today:
color = 'danger'
elif (deadline - today).days < 7:
color = 'warning'
else:
color = 'secondary'
dashboard_data[journal.id]['tax_return_button_color'] = color
dashboard_data[journal.id]['tax_return_button_label'] = self.env._("Tax Returns")
def action_open_bank_balance_in_gl(self):
''' Show the bank balance inside the General Ledger report.
:return: An action opening the General Ledger.
'''
self.ensure_one()
action = self.env["ir.actions.actions"]._for_xml_id("account_reports.action_account_report_general_ledger")
action['context'] = dict(ast.literal_eval(action['context']), default_filter_accounts=self.default_account_id.code)
return action

View File

@@ -0,0 +1,21 @@
from collections.abc import Collection
from odoo import api, models
class AccountJournalGroup(models.Model):
_inherit = "account.journal.group"
def _cache_local_gaap(self):
local_gaap = self.browse(['local_gaap'])
self._fields['name']._update_cache(local_gaap, self.env._("Local Gaap"))
self._fields['sequence']._update_cache(local_gaap, 0)
self._fields['included_journal_ids']._update_cache(local_gaap, tuple(self.env['account.journal'].with_context(active_test=False).search([('journal_group_id', '=', False)]).ids))
@api.private
def fetch(self, field_names: Collection[str] | None = None) -> None:
real_ids = self._ids
if 'local_gaap' in self._ids:
real_ids = [id_ for id_ in self._ids if id_ != 'local_gaap']
self._cache_local_gaap()
super(AccountJournalGroup, self.browse(real_ids)).fetch(field_names)

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,32 @@
from odoo import api, models
class AccountLockException(models.Model):
_inherit = 'account.lock_exception'
@api.model_create_multi
def create(self, vals_list):
exceptions = super().create(vals_list)
if any(exception.lock_date_field in ('tax_lock_date', 'fiscalyear_lock_date') for exception in exceptions):
self.env.ref('account_reports.ir_cron_garbage_collect_snapshots')._trigger()
exceptions._create_report_snapshot_triggers_at_end_datetime()
return exceptions
def write(self, vals):
if any(lock_date_field in vals.get('lock_date_field', {}) for lock_date_field in ('tax_lock_date', 'fiscalyear_lock_date')):
self.env.ref('account_reports.ir_cron_garbage_collect_snapshots')._trigger()
rslt = super().write(vals)
if 'end_datetime' in vals:
self._create_report_snapshot_triggers_at_end_datetime()
return rslt
def _create_report_snapshot_triggers_at_end_datetime(self):
for end_datetime in set(self.filtered(lambda x: x.lock_date_field in ('tax_lock_date', 'fiscalyear_lock_date')).mapped('end_datetime')):
if end_datetime:
self.env.ref('account_reports.ir_cron_create_snapshots')._trigger(at=end_datetime)

View File

@@ -0,0 +1,70 @@
from odoo import _, models, fields
class AccountMove(models.Model):
_inherit = "account.move"
closing_return_id = fields.Many2one(comodel_name='account.return', index='btree_not_null', copy=False)
def action_open_tax_return(self):
return self.closing_return_id.action_open_account_return()
def unlink(self):
for move in self:
if move.closing_return_id:
if len(move.closing_return_id.company_ids) == 1:
move.closing_return_id.message_post(
body=_("Closing entry deleted"),
message_type='comment',
)
else:
move.closing_return_id.message_post(
body=_("Closing entry deleted for company %s", move.closing_return_id.company_id),
message_type='comment',
)
return super().unlink()
def _post(self, soft=True):
posted_moves = super()._post(soft)
posted_moves._update_accounts_audit_status()
return posted_moves
def button_draft(self):
posted_moves = self.filtered(lambda move: move.state == 'posted')
res = super().button_draft()
posted_moves._update_accounts_audit_status()
return res
def _update_accounts_audit_status(self):
if not self:
return
all_statuses = self.env['account.audit.account.status'].sudo().search([
('account_id', 'in', self.line_ids.account_id.ids),
('status', 'in', (False, 'reviewed', 'supervised')),
('audit_id.company_ids', 'in', self.company_id.ids),
])
if not all_statuses:
return
account_to_statuses = all_statuses.grouped('account_id')
audits = all_statuses.mapped('audit_id')
audit_id_to_dates = {
audit.id: {
'date_from': audit.date_from,
'date_to': audit.date_to
} for audit in audits
}
statuses_to_update = self.env['account.audit.account.status']
empty_status = self.env['account.audit.account.status']
for line in self.line_ids:
matching_statuses = account_to_statuses.get(line.account_id, empty_status).filtered(
lambda status: audit_id_to_dates[status.audit_id.id]['date_from'] <= line.date <= audit_id_to_dates[status.audit_id.id]['date_to']
)
statuses_to_update |= matching_statuses
if statuses_to_update:
statuses_to_update.status = 'todo'

View File

@@ -0,0 +1,145 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, api, fields, models
from odoo.exceptions import UserError
from odoo.tools import SQL
from odoo.tools.sql import table_columns
class AccountMoveLine(models.Model):
_inherit = "account.move.line"
exclude_bank_lines = fields.Boolean(compute='_compute_exclude_bank_lines', store=True)
analytic_coverage = fields.Float(
string="Analytic Coverage",
compute='_compute_analytic_coverage',
compute_sql='_compute_sql_analytic_coverage',
compute_sudo=True,
groups='analytic.group_analytic_accounting',
)
cta_value = fields.Monetary(
string="CTA",
compute='_compute_cta_value',
compute_sql='_compute_sql_cta_value',
compute_sudo=True,
currency_field='consolidation_currency_id',
)
@api.depends('journal_id')
def _compute_exclude_bank_lines(self):
for move_line in self:
move_line.exclude_bank_lines = move_line.account_id != move_line.journal_id.default_account_id
@api.constrains('tax_ids', 'tax_tag_ids')
def _check_taxes_on_closing_entries(self):
for aml in self:
if aml.move_id.closing_return_id and (aml.tax_ids or aml.tax_tag_ids):
raise UserError(_("You cannot add taxes on a tax closing move line."))
@api.depends('product_id', 'product_uom_id', 'move_id.closing_return_id')
def _compute_tax_ids(self):
""" Some special cases may see accounts used in tax closing having default taxes.
They would trigger the constrains above, which we don't want. Instead, we don't trigger
the tax computation in this case.
"""
# EXTEND account
lines_to_compute = self.filtered(lambda line: not line.move_id.closing_return_id)
(self - lines_to_compute).tax_ids = False
super(AccountMoveLine, lines_to_compute)._compute_tax_ids()
def _compute_sql_cta_value(self, table):
current_rate_table = table._with_model(self.with_context(currency_translation='current'))
return SQL("%s - %s", table.consolidation_balance, current_rate_table.consolidation_balance)
@api.depends('consolidation_balance', 'consolidation_rate', 'balance')
def _compute_cta_value(self):
for line in self:
line.cta_value = line.consolidation_balance - line.with_context(currency_translation='current').consolidation_balance
def _get_attachment_domains(self):
attachment_domains = super()._get_attachment_domains()
if self.move_id.closing_return_id:
attachment_domains.append([('res_model', '=', 'account.return'), ('res_id', 'in', self.move_id.closing_return_id.ids)])
return attachment_domains
@api.model
def _get_attachment_by_record(self, id_model2attachments, move_line):
attachment_id = super()._get_attachment_by_record(id_model2attachments, move_line)
if not attachment_id and move_line.move_id.closing_return_id:
attachment_id = id_model2attachments.get(('account.return', move_line.move_id.closing_return_id.id))
return attachment_id
@api.model
def _prepare_aml_shadowing_for_report(self, change_equivalence_dict, prefix_fields=False):
""" Prepares the fields lists for creating a temporary table shadowing the account_move_line one.
This is used to switch the computation mode of the reports, with analytics or financial budgets, for example.
:param change_equivalence_dict: A dict, in the form {aml_field: sql_equivalence}, where:
- aml_field: is a string containing the name of field of account.move.line
- sql_equivalence: is the value to use to shadow aml_field. It can be an SQL object; if
it's not, it'll be escaped in the query.
:param prefix_fields: True if you want the returned stored fields to be prefixed with the `account_move_line` table.
:return: A tuple of 2 SQL objects, so that:
- The first one is the fields list to pass into the INSERT TO part of the query filling up the temporary table
- The second one contains the field values to insert into the SELECT clause of the same query, in the same order
as in the first element of the returned tuple.
"""
line_fields = self.env['account.move.line'].fields_get(attributes=["translate"])
stored_fields = {fld for fld in table_columns(self.env.cr, 'account_move_line') if fld in line_fields}
fields_to_insert = []
for fname in stored_fields:
if fname in change_equivalence_dict:
fields_to_insert.append(SQL(
"%(original)s AS %(asname)s",
original=change_equivalence_dict[fname],
asname=SQL.identifier(fname),
))
else:
typecast = self.env['account.move.line']._fields[fname].stored_sql_column_type
fields_to_insert.append(SQL(
"CAST(NULL AS %(typecast)s) AS %(fname)s",
typecast=typecast,
fname=SQL.identifier(fname),
))
return (
SQL(', ').join(
SQL.identifier('account_move_line', fname) if prefix_fields else SQL.identifier(fname)
for fname in stored_fields
),
SQL(', ').join(fields_to_insert)
)
def _affect_tax_report(self):
return super()._affect_tax_report() or (self.move_id.closing_return_id and not self.env.context.get('account_bypass_tax_closing_lock_check'))
def _compute_sql_analytic_coverage(self, table):
plan_id = self.env.context.get('selected_analytic_plan')
if not plan_id:
return SQL("0.0")
return SQL("""
(SELECT COALESCE(SUM(CAST(distribution.value AS FLOAT)) / 100, 0)
FROM jsonb_each_text(%(distribution)s) AS distribution(key, value)
WHERE EXISTS (
SELECT 1
FROM regexp_split_to_table(distribution.key, ',') AS accounts
JOIN account_analytic_account ON account_analytic_account.id = CAST(accounts AS INTEGER)
WHERE account_analytic_account.plan_id = %(plan_id)s
))
""",
distribution=table.analytic_distribution,
plan_id=plan_id,
)
def _compute_analytic_coverage(self):
query = self._search([('id', 'in', self.ids)])
line2coverage = dict(self.env.execute_query(query.select(
query.table.id,
query.table.analytic_coverage,
)))
for line in self:
line.analytic_coverage = line2coverage[line._origin.id]

View File

@@ -0,0 +1,375 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import _, models
from odoo.exceptions import UserError
from odoo.tools import SQL, float_is_zero
class AccountMulticurrencyRevaluationReportHandler(models.AbstractModel):
"""Manage Unrealized Gains/Losses.
In multi-currencies environments, we need a way to control the risk related
to currencies (in case some are higthly fluctuating) and, in some countries,
some laws also require to create journal entries to record the provisionning
of a probable future expense related to currencies. Hence, people need to
create a journal entry at the beginning of a period, to make visible the
probable expense in reports (and revert it at the end of the period, to
recon the real gain/loss.
"""
_name = 'account.multicurrency.revaluation.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Multicurrency Revaluation Report Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
active_currencies = self.env['res.currency'].search([('active', '=', True)])
if len(active_currencies) < 2:
raise UserError(_("You need to activate more than one currency to access this report."))
active_currencies = active_currencies.with_context(
to_currency=self.env.company.currency_id.id,
date=options['date']['date_to']
)
options['currency_rates'] = {
str(currency.id): {
'currency_id': currency.id,
'currency_name': currency.name,
'currency_main': self.env.company.currency_id.name,
'rate': (currency.rate
if not previous_options.get('currency_rates', {}).get(str(currency.id), {}).get('rate') else
float(previous_options['currency_rates'][str(currency.id)]['rate'])),
} for currency in active_currencies
}
for currency_rates in options['currency_rates'].values():
if currency_rates['rate'] == 0:
raise UserError(_("The currency rate cannot be equal to zero"))
options['company_currency'] = options['currency_rates'].pop(str(self.env.company.currency_id.id))
options['custom_rate'] = any(
not float_is_zero(cr['rate'] - active_currencies.browse(cr['currency_id']).rate, 20)
for cr in options['currency_rates'].values()
)
options['multi_currency'] = True
options['buttons'].append({'name': _('Adjustment Entry'), 'sequence': 30, 'action': 'action_multi_currency_revaluation_open_revaluation_wizard', 'always_show': True})
options['custom_display_config'] = {
'components': {
'AccountReportFilters': 'MulticurrencyRevaluationReportFilters',
},
'templates': {
'AccountReportLineName': 'account_reports.MulticurrencyRevaluationReportLineName',
},
}
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
if len(self.env.companies) > 1:
warnings['account_reports.multi_currency_revaluation_report_warning_multicompany'] = {'alert_type': 'warning'}
if options['custom_rate']:
warnings['account_reports.multi_currency_revaluation_report_warning_custom_rate'] = {'alert_type': 'warning'}
def _custom_line_postprocessor(self, report, options, lines):
line_to_adjust_id = self.env.ref('account_reports.multicurrency_revaluation_to_adjust').id
line_excluded_id = self.env.ref('account_reports.multicurrency_revaluation_excluded').id
rslt = []
for index, line in enumerate(lines):
res_model_name, res_id = report._get_model_info_from_id(line.id)
if res_model_name == 'account.report.line' and (
(res_id == line_to_adjust_id and report._get_model_info_from_id(lines[index + 1].id) == ('account.report.line', line_excluded_id)) or
(res_id == line_excluded_id and index == len(lines) - 1)
):
# 'To Adjust' and 'Excluded' lines need to be hidden if they have no child
continue
elif res_model_name == 'res.currency':
# Include the rate in the currency_id group lines
line.name = '{for_cur} (1 {comp_cur} = {rate:.6} {for_cur})'.format(
for_cur=line.name,
comp_cur=self.env.company.currency_id.display_name,
rate=float(options['currency_rates'][str(res_id)]['rate']),
)
elif res_model_name == 'account.account':
# Mark the included/excluded lines, so that the custom component templates knows what label to put on them
line.get_custom()['is_included_line'] = report._get_res_id_from_line_id(line.id, 'account.account') == line_to_adjust_id
# Inject the related model into the line dict in order to use it on the custom component template on js side to display buttons
line.get_custom()['cur_revaluation_line_model'] = res_model_name
rslt.append(line)
return rslt
def _custom_groupby_line_completer(self, report, options, line_data, current_groupby):
model_info_from_id = report._get_model_info_from_id(line_data.id)
if model_info_from_id[0] == 'res.currency':
line_data.unfolded = True
line_data.unfoldable = False
def action_multi_currency_revaluation_open_revaluation_wizard(self, options):
"""Open the revaluation wizard."""
form = self.env.ref('account_reports.view_account_multicurrency_revaluation_wizard', False)
return {
'name': _("Make Adjustment Entry"),
'type': 'ir.actions.act_window',
'res_model': 'account.multicurrency.revaluation.wizard',
'view_mode': 'form',
'view_id': form.id,
'views': [(form.id, 'form')],
'multi': 'True',
'target': 'new',
'context': {
**self.env.context,
'multicurrency_revaluation_report_options': options,
},
}
# ACTIONS
def action_multi_currency_revaluation_open_general_ledger(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
account_id = report._get_res_id_from_line_id(params['line_id'], 'account.account')
account_line_id = report._get_generic_line_id('account.account', account_id)
general_ledger_options = self.env.ref('account_reports.general_ledger_report').get_options(options)
general_ledger_options['unfolded_lines'] = [account_line_id]
general_ledger_action = self.env['ir.actions.actions']._for_xml_id('account_reports.action_account_report_general_ledger')
general_ledger_action['params'] = {
'options': general_ledger_options,
'ignore_session': True,
}
return general_ledger_action
def action_multi_currency_revaluation_toggle_provision(self, options, params):
""" Include/exclude an account from the provision. """
res_ids_map = self.env['account.report']._get_res_ids_from_line_id(params['line_id'], ['res.currency', 'account.account'])
account = self.env['account.account'].browse(res_ids_map['account.account'])
currency = self.env['res.currency'].browse(res_ids_map['res.currency'])
if currency in account.exclude_provision_currency_ids:
account.exclude_provision_currency_ids -= currency
else:
account.exclude_provision_currency_ids += currency
return {
'type': 'ir.actions.client',
'tag': 'reload',
}
def action_multi_currency_revaluation_open_currency_rates(self, options, params=None):
""" Open the currency rate list. """
currency_id = self.env['account.report']._get_res_id_from_line_id(params['line_id'], 'res.currency')
return {
'type': 'ir.actions.act_window',
'name': _('Currency Rates (%s)', self.env['res.currency'].browse(currency_id).display_name),
'views': [(False, 'list')],
'res_model': 'res.currency.rate',
'context': {**self.env.context, **{'default_currency_id': currency_id, 'active_id': currency_id}},
'domain': [('currency_id', '=', currency_id)],
}
def _report_engine_multi_currency_revaluation_to_adjust(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._multi_currency_revaluation_get_custom_lines(options, 'to_adjust', formulas_dict, current_groupby)
def _report_engine_multi_currency_revaluation_excluded(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._multi_currency_revaluation_get_custom_lines(options, 'excluded', formulas_dict, current_groupby)
def _multi_currency_revaluation_get_custom_lines(self, options, line_code, formulas_dict, current_groupby):
def build_result_dict(report, query_res):
return {
'balance_currency': query_res['balance_currency'] if len(query_res['currency_id']) == 1 else None,
'currency_id': query_res['currency_id'][0] if len(query_res['currency_id']) == 1 else None,
'balance_operation': query_res['balance_operation'],
'balance_current': query_res['balance_current'],
'adjustment': query_res['adjustment'],
'has_sublines': True,
}
# No need to run any SQL if we're computing the main line: it does not display any total
if not current_groupby:
return {next(iter(formulas_dict.values())): {
'balance_currency': None,
'currency_id': None,
'balance_operation': None,
'balance_current': None,
'adjustment': None,
'has_sublines': True,
}}
report = self.env['account.report'].browse(options['report_id'])
report._check_groupby_fields([current_groupby])
custom_currency_table_query = SQL("(VALUES %s)", SQL(", ").join(
SQL("(%(currency_id)s, %(rate)s)", **cur)
for cur in options['currency_rates'].values()
))
date_to = options['date']['date_to']
select_part_not_an_exchange_move_id = SQL(
"""
NOT EXISTS (
SELECT 1
FROM account_partial_reconcile part_exch
WHERE part_exch.exchange_move_id = account_move_line.move_id
AND part_exch.max_date <= %s
)
""",
date_to
)
query = report._get_report_query(options, 'strict_range')
groupby_field_sql = self.env['account.move.line']._field_to_sql("account_move_line", current_groupby, query)
full_query = SQL(
"""
WITH custom_currency_table(currency_id, rate) AS (%(custom_currency_table_query)s)
-- Final select that gets the following lines:
-- (where there is a change in the rates of currency between the creation of the move and the full payments)
-- - Moves that don't have a payment yet at a certain date
-- - Moves that have a partial but are not fully paid at a certain date
SELECT
subquery.grouping_key,
ARRAY_AGG(DISTINCT(subquery.currency_id)) AS currency_id,
SUM(subquery.balance_currency) AS balance_currency,
SUM(subquery.balance_operation) AS balance_operation,
SUM(subquery.balance_current) AS balance_current,
SUM(subquery.adjustment) AS adjustment
FROM (
-- Get moves that have at least one partial at a certain date and are not fully paid at that date
SELECT
%(groupby_field_sql)s AS grouping_key,
ROUND(account_move_line.balance - SUM(ara.amount_debit) + SUM(ara.amount_credit), aml_comp_currency.decimal_places) AS balance_operation,
ROUND(account_move_line.amount_currency - SUM(ara.amount_debit_currency) + SUM(ara.amount_credit_currency), aml_currency.decimal_places) AS balance_currency,
ROUND(account_move_line.amount_currency - SUM(ara.amount_debit_currency) + SUM(ara.amount_credit_currency), aml_currency.decimal_places) / custom_currency_table.rate AS balance_current,
(
-- adjustment is computed as: balance_current - balance_operation
ROUND( account_move_line.amount_currency - SUM(ara.amount_debit_currency) + SUM(ara.amount_credit_currency), aml_currency.decimal_places) / custom_currency_table.rate
- ROUND(account_move_line.balance - SUM(ara.amount_debit) + SUM(ara.amount_credit), aml_comp_currency.decimal_places)
) AS adjustment,
account_move_line.currency_id AS currency_id,
account_move_line.id AS aml_id
FROM %(table_references)s,
account_account AS account,
res_currency AS aml_currency,
res_currency AS aml_comp_currency,
custom_currency_table,
-- Get for each move line the amount residual and amount_residual currency
-- both for matched "debit" and matched "credit" the same way as account.move.line
-- '_compute_amount_residual()' method does
-- (using LATERAL greatly reduce the number of lines for which we have to compute it)
LATERAL (
-- Get sum of matched "debit" amount and amount in currency for related move line at date
SELECT COALESCE(SUM(part.amount), 0.0) AS amount_debit,
ROUND(
SUM(part.debit_amount_currency),
curr.decimal_places
) AS amount_debit_currency,
0.0 AS amount_credit,
0.0 AS amount_credit_currency,
account_move_line.currency_id AS currency_id,
account_move_line.id AS aml_id
FROM account_partial_reconcile part
JOIN res_currency curr ON curr.id = part.debit_currency_id
WHERE account_move_line.id = part.debit_move_id
AND part.max_date <= %(date_to)s
GROUP BY aml_id,
curr.decimal_places
UNION
-- Get sum of matched "credit" amount and amount in currency for related move line at date
SELECT 0.0 AS amount_debit,
0.0 AS amount_debit_currency,
COALESCE(SUM(part.amount), 0.0) AS amount_credit,
ROUND(
SUM(part.credit_amount_currency),
curr.decimal_places
) AS amount_credit_currency,
account_move_line.currency_id AS currency_id,
account_move_line.id AS aml_id
FROM account_partial_reconcile part
JOIN res_currency curr ON curr.id = part.credit_currency_id
WHERE account_move_line.id = part.credit_move_id
AND part.max_date <= %(date_to)s
GROUP BY aml_id,
curr.decimal_places
) AS ara
WHERE %(search_condition)s
AND account_move_line.account_id = account.id
AND account_move_line.currency_id = aml_currency.id
AND account_move_line.company_currency_id = aml_comp_currency.id
AND account_move_line.currency_id = custom_currency_table.currency_id
AND account.account_type NOT IN ('income', 'income_other', 'expense', 'expense_depreciation', 'expense_direct_cost', 'off_balance')
AND (
account.currency_id != account_move_line.company_currency_id
OR (
account.account_type IN ('asset_receivable', 'liability_payable')
AND (account_move_line.currency_id != account_move_line.company_currency_id)
)
)
AND %(exist_condition)s (
SELECT 1
FROM account_account_exclude_res_currency_provision
WHERE account_account_id = account_move_line.account_id
AND res_currency_id = account_move_line.currency_id
)
AND (%(select_part_not_an_exchange_move_id)s)
GROUP BY account_move_line.id, grouping_key, aml_comp_currency.decimal_places, aml_currency.decimal_places, custom_currency_table.rate
HAVING ROUND(account_move_line.balance - SUM(ara.amount_debit) + SUM(ara.amount_credit), aml_comp_currency.decimal_places) != 0
OR ROUND(account_move_line.amount_currency - SUM(ara.amount_debit_currency) + SUM(ara.amount_credit_currency), aml_currency.decimal_places) != 0.0
UNION
-- Moves that don't have a payment yet at a certain date
SELECT
%(groupby_field_sql)s AS grouping_key,
account_move_line.balance AS balance_operation,
account_move_line.amount_currency AS balance_currency,
account_move_line.amount_currency / custom_currency_table.rate AS balance_current,
account_move_line.amount_currency / custom_currency_table.rate - account_move_line.balance AS adjustment,
account_move_line.currency_id AS currency_id,
account_move_line.id AS aml_id
FROM %(table_references)s
JOIN account_account account ON account_move_line.account_id = account.id
JOIN custom_currency_table ON custom_currency_table.currency_id = account_move_line.currency_id
WHERE %(search_condition)s
AND account.account_type NOT IN ('income', 'income_other', 'expense', 'expense_depreciation', 'expense_direct_cost', 'off_balance')
AND (
account.currency_id != account_move_line.company_currency_id
OR (
account.account_type IN ('asset_receivable', 'liability_payable')
AND (account_move_line.currency_id != account_move_line.company_currency_id)
)
)
AND %(exist_condition)s (
SELECT 1
FROM account_account_exclude_res_currency_provision
WHERE account_account_id = account_id
AND res_currency_id = account_move_line.currency_id
)
AND (%(select_part_not_an_exchange_move_id)s)
AND NOT EXISTS (
SELECT 1 FROM account_partial_reconcile part
WHERE (part.debit_move_id = account_move_line.id OR part.credit_move_id = account_move_line.id)
AND part.max_date <= %(date_to)s
)
AND (account_move_line.balance != 0.0 OR account_move_line.amount_currency != 0.0)
) subquery
GROUP BY grouping_key
ORDER BY grouping_key
""",
groupby_field_sql=groupby_field_sql,
custom_currency_table_query=custom_currency_table_query,
exist_condition=SQL('NOT EXISTS') if line_code == 'to_adjust' else SQL('EXISTS'),
table_references=query.from_clause,
date_to=date_to,
search_condition=query.where_clause,
select_part_not_an_exchange_move_id=select_part_not_an_exchange_move_id,
)
self.env.cr.execute(full_query)
query_res_lines = self.env.cr.dictfetchall()
rslt = []
for query_res in query_res_lines:
grouping_key = query_res['grouping_key']
rslt.append((grouping_key, build_result_dict(report, query_res)))
return {next(iter(formulas_dict.values())): rslt}

View File

@@ -0,0 +1,684 @@
import re
from collections import defaultdict
from odoo import api, fields, models
from odoo.addons.account_reports.models.account_report_snapshot import snapshotable_engine
from odoo.tools import SQL
FIELDS_TAKEN_FROM_PARTIALS = ['id', 'partner_id', 'debit', 'credit', 'amount_currency', 'balance']
NAME_PATTERN = re.compile(r"^[^()]+\s*(?:\([^()]+\))?")
class AccountPartnerLedgerReportHandler(models.AbstractModel):
_name = 'account.partner.ledger.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Partner Ledger Custom Handler'
####################################################
# OVERRIDES
####################################################
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
domain = []
company_ids = report.get_report_company_ids(options)
exch_code = self.env['res.company'].browse(company_ids).mapped('currency_exchange_journal_id')
if exch_code:
domain += ['!', '&', '&', '&', ('credit', '=', 0.0), ('debit', '=', 0.0), ('amount_currency', '!=', 0.0), ('journal_id', 'in', exch_code.ids)]
if options['export_mode'] == 'print' and options.get('filter_search_bar'):
domain += [
'|', ('matched_debit_ids.debit_move_id.partner_id.name', 'ilike', options['filter_search_bar']),
'|', ('matched_credit_ids.credit_move_id.partner_id.name', 'ilike', options['filter_search_bar']),
'|', ('partner_id.name', 'ilike', options['filter_search_bar']),
('partner_id', '=', False),
]
options['forced_domain'] = options.get('forced_domain', []) + domain
if self.env.user.has_group('base.group_multi_currency'):
options['multi_currency'] = True
else:
options['columns'] = [col for col in options['columns'] if col['expression_label'] not in {'amount_currency'}]
accounts = self.env['account.account']
if not accounts.search_count([('code', '!=', False), *accounts._check_company_domain(self.env.company)], limit=1):
options['columns'] = [col for col in options['columns'] if col['expression_label'] != 'account_code']
options['custom_display_config'] = {
'css_custom_class': 'partner_ledger',
'templates': {
'AccountReportLineName': 'account_reports.PartnerLedgerLineName',
},
}
def _get_custom_groupby_map(self):
def partner_line_label_builder(ids):
valid_ids = [id for id in ids if id]
partners = self.env['res.partner'].browse(valid_ids).sorted('name')
partner_names = partners.mapped('name')
res = dict(zip(partners.ids, partner_names))
if None in ids:
res[None] = self.env._("Unknown Partner")
return res
def move_line_label_builder(keys):
if not keys:
return {}
# The fake lines have negative ids, that's why to take the absolute value
lines = self.env['account.move.line'].browse(abs(key) for key in keys if key is not None)
key_to_label_dict = dict(zip(
[key for key in keys if key is not None],
lines.mapped(lambda line: match.group(0).strip() if (match := NAME_PATTERN.match(line.display_name or '')) else line.display_name),
))
if None in keys:
# Initial balance always displayed first.
return {
None: self.env._("Initial Balance"),
**key_to_label_dict,
}
return key_to_label_dict
return {
'partner_id': {
'model': 'res.partner',
'label_builder': partner_line_label_builder,
'domain_builder': lambda grouping_key: [] # Handled in _report_expand_unfoldable_line_with_groupby
},
'id': {
'model': None,
'caret_builder': lambda grouping_key: bool(grouping_key) and 'id',
'label_builder': move_line_label_builder,
'is_column_cumulative': lambda expr_label: expr_label == 'balance',
'pre_load_more_key_sort': lambda all_group_results: 1 if all_group_results[0] else -1,
},
}
def _caret_options_initializer(self):
default_caret = self.env['account.report']._caret_options_initializer_default()
return {
**default_caret,
'id': [
{'name': self.env._("View Journal Entry"), 'action': 'caret_option_open_record_form_custom_id_groupby', 'action_param': 'move_id'},
]
}
def _report_expand_unfoldable_line_with_groupby(self, line_dict_id, groupby, options, unfold_all_batch_data=None, limit_to_load=None):
report = self.env['account.report'].browse(options['report_id'])
res_ids_map = report._get_res_ids_from_line_id(line_dict_id, ['res.partner'])
if 'res.partner' in res_ids_map:
# Restrict the computation to the expanded partner group (model_id is None for 'Unknown Partner').
options = options | {'partner_ledger_expand_partner': res_ids_map['res.partner']}
return report._report_expand_unfoldable_line_with_groupby(
line_dict_id,
groupby,
options,
unfold_all_batch_data=unfold_all_batch_data,
limit_to_load=limit_to_load,
)
def _custom_unfold_all_batch_data_generator(self, report, options, lines_to_expand_by_function):
def build_full_sub_groupby_key(report_line_id, full_sub_groupby_key_elements, current_groupby):
return f"[{report_line_id}]{','.join(full_sub_groupby_key_elements)}=>{current_groupby}"
def add_line_dict_to_rslt_dict(rslt, line_dict, column_group_index, key, groupby, value_key_by_expression):
for expression, value_key in value_key_by_expression.items():
rslt[key][column_group_index][expression]['value'].append((line_dict[groupby], line_dict.get(value_key)))
if groupby != 'id':
rslt[key][column_group_index][expression]['sublines_info'].add(line_dict[groupby])
rslt = defaultdict(lambda: defaultdict(
lambda: defaultdict(
lambda: {
'value': [],
'sublines_info': set(),
}
)
))
for expand_function_name, lines_to_expand in lines_to_expand_by_function.items():
for line_to_expand in lines_to_expand:
if expand_function_name == '_report_expand_unfoldable_line_with_groupby':
report_line_id = report._get_res_id_from_line_id(line_to_expand.id, 'account.report.line')
report_line = self.env['account.report.line'].browse(report_line_id)
# We need to get the expression to compute without the workaround for snapshot
# So the balance aggregation is computed directly without using the aggregation
# In that case, we need to remove from expressions the init_balance and period_balance expression
expressions = report_line.expression_ids.filtered(
lambda expr: expr.label not in ('period_balance', 'init_balance')
)
groupbys = report_line._get_groupby(options).split(',')
# Don't depend on aggregation for unfold_all but calculate the 'balance' directly with 'from_beginning'
subformulas_rules = self._get_subformulas_rules()
value_key_by_expression = {}
for expression in expressions:
if expression.engine == 'custom':
value_key_by_expression[expression] = expression.subformula
elif expression.engine == 'aggregation' and expression.label in subformulas_rules:
value_key_by_expression[expression] = expression.label
subformulas = list({value_key for value_key in value_key_by_expression.values() if value_key})
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
for i, groupby in enumerate(groupbys):
if groupby != 'id':
line_dicts = self._get_aggregated_lines(subformulas, column_group_options, groupbys[:i + 1], 'from_beginning')
else:
line_dicts = self._get_move_lines(subformulas, column_group_options, groupbys[:i + 1], 'from_beginning')
for line_dict in line_dicts:
key = build_full_sub_groupby_key(report_line_id, [f"{groupby_}:{line_dict[groupby_]}" for groupby_ in groupbys[:i]], groupby)
add_line_dict_to_rslt_dict(rslt, line_dict, column_group_index, key, groupby, value_key_by_expression)
return rslt
def _custom_line_postprocessor(self, report, options, lines):
today = fields.Date.context_today(report)
monetary_columns_indexes = [i for i, col in enumerate(options['columns']) if col.get('figure_type') == 'monetary']
date_maturity_index_col = next((i for i, col in enumerate(options['columns']) if col.get('expression_label') == 'date_maturity'), None)
colname_to_idx = {col['expression_label']: idx for idx, col in enumerate(options.get('columns', []))}
init_balance = 0
for line in lines:
line_col = line.columns
next_groupby = line.groupby.split(',')[0] if line.groupby else None
markup = report._get_markup(line.id)
grouping_key = report._get_model_info_from_id(line.id)[1]
if next_groupby == 'id' and markup != 'load_more':
init_balance = 0
if isinstance(markup, dict) and markup.get('groupby', '') == 'id':
if date_maturity_index_col:
date_maturity = line_col[date_maturity_index_col].no_format
if date_maturity and date_maturity < today:
line_col[date_maturity_index_col].css_class = 'text-danger'
if not options.get('unfold_all') and 'balance' in colname_to_idx:
# The batch data generator use a different method by avoiding using the snapshots
# Instead of computing init_balance and period_balance separately, it does it together
# resulting with the correcty cumulative balance.
if grouping_key is None:
init_balance = line.columns[colname_to_idx['balance']].no_format
else:
current_balance_column = line.columns[colname_to_idx['balance']]
new_balance = init_balance + current_balance_column.no_format
line.columns[colname_to_idx['balance']] = report._build_column_data(
new_balance,
options['columns'][colname_to_idx['balance']],
options,
)
elif markup == 'load_more' and 'balance' in colname_to_idx:
current_balance_column = line.columns[colname_to_idx['balance']]
new_balance = init_balance + current_balance_column.no_format
line.columns[colname_to_idx['balance']] = report._build_column_data(
new_balance,
options['columns'][colname_to_idx['balance']],
options,
)
for col_index in monetary_columns_indexes:
line_col_details = line_col[col_index]
no_format_value = line_col_details.no_format
if no_format_value and no_format_value < 0:
line_col_details.css_class = 'text-info'
return lines
####################################################
# CORE
####################################################
@api.model
def _get_subformulas_rules(self):
return {
'journal_code': {'to_sql': lambda query: query.table.journal_id.code},
'invoice_date': {
'to_sql': lambda _query: SQL('COALESCE(account_move_line.invoice_date, account_move_line.date)'),
},
'_currency_amount_currency': {'field': 'currency_id'},
'init_balance': {
'field': 'balance',
'from_beginning': True,
},
'balance': {
'from_beginning': True,
'cumulative_sum': True,
},
'period_balance': {
'field': 'balance',
'cumulative_sum': True,
},
}
@api.model
def _report_engine_partner_ledger_report(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
expressions = self.env['account.report.expression']
for formula_expressions in formulas_dict.values():
expressions |= formula_expressions
subformulas = expressions.mapped('subformula')
if not current_groupby:
totals = self._get_aggregated_lines(subformulas, options, [], date_scope=date_scope)
engine_res = {**totals[0], 'has_sublines': True} if totals else {subformula: None for subformula in subformulas} | {'has_sublines': False}
return {next(iter(formulas_dict.values())): engine_res}
if current_groupby == 'id':
groupbys = [groupby.strip() for groupby in expressions.report_line_id._get_groupby(options).split(',')]
line_dicts = self._get_move_lines(subformulas, options, groupbys, date_scope)
else:
line_dicts = self._get_aggregated_lines(subformulas, options, [current_groupby], date_scope=date_scope)
return {next(iter(formulas_dict.values())): [(line_dict[current_groupby], line_dict | {'has_sublines': current_groupby != 'id'}) for line_dict in line_dicts]}
def _report_engine_partner_ledger_initial_balance(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
expressions_key = next(iter(formulas_dict.values()))
subengine_result = self._report_engine_partner_ledger_initial_balance_subengine(options, date_scope, formulas_dict, current_groupby)
currency = self.env.company.currency_id
if not current_groupby:
total_init_balance = subengine_result[expressions_key]['init_balance']
return {expressions_key: {'init_balance': total_init_balance or 0.0, 'has_sublines': False}}
merged_groups = dict(subengine_result[expressions_key])
if current_groupby == 'partner_id' or 'partner_ledger_expand_partner' in options:
for grouping_key, balance_delta in self._get_no_partner_reconciled_delta(options, date_scope, current_groupby).items():
group_values = merged_groups.setdefault(grouping_key, {'init_balance': 0.0, 'has_sublines': True})
group_values['init_balance'] += balance_delta
return {
expressions_key: [
(grouping_key, group_values)
for grouping_key, group_values in merged_groups.items()
if not currency.is_zero(group_values['init_balance'])
],
}
@snapshotable_engine(result_aggregators={'init_balance': sum, 'has_sublines': max}, sub_engine_of='_report_engine_partner_ledger_initial_balance')
def _report_engine_partner_ledger_initial_balance_subengine(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
""" Summable part of the partner ledger's initial balance: plain sums grouped on the move lines' own partner_id """
report = self.env['account.report'].browse(options['report_id'])
expressions_key = next(iter(formulas_dict.values()))
query = report._get_report_query(options, date_scope)
balance_expr = SQL('SUM(%s * %s)', query.table.balance, query.table.consolidation_rate)
if not current_groupby:
row = self.env.execute_query_dict(query.select(SQL('%s AS init_balance', balance_expr)))[0]
return {expressions_key: {'init_balance': row['init_balance'] or 0.0, 'has_sublines': False}}
if 'partner_ledger_expand_partner' in options:
query.add_where(SQL('partner_id = %s', options['partner_ledger_expand_partner']))
if current_groupby == 'id':
groupby_expr = SQL('NULL')
else:
groupby_expr = query.table[current_groupby]
query.groupby = groupby_expr
rows = self.env.execute_query_dict(query.select(
SQL('%s AS grouping_key', groupby_expr),
SQL('%s AS init_balance', balance_expr),
))
return {
expressions_key: [
(row['grouping_key'], {'init_balance': row['init_balance'] or 0.0, 'has_sublines': False})
for row in rows
],
}
@api.model
def _get_no_partner_reconciled_delta(self, options, date_scope, current_groupby):
"""
Calculate the amounts to transfer from 'Unknown Partner' group to a partner for partner-less lines that have been reconciled.
This correction is recalculated on the whole period at every call: it cannot
be part of snapshots, since reconciling can alter it at any time, even for lines in locked periods.
"""
report = self.env['account.report'].browse(options['report_id'])
partner_ids = options.get('partner_ids')
query = report._get_report_query({**options, 'partner_ids': []}, date_scope, domain=[('partner_id', '=', False)])
self._add_partials_data_join(query)
query.add_where(SQL('partials_data.id IS NOT NULL'))
if current_groupby != 'id':
groupby_expr = self._get_expr(current_groupby, query)
query.groupby = groupby_expr
else:
groupby_expr = SQL('NULL')
partner_expr = self._get_expr('partner_id', query)
if partner_ids:
query.add_where(SQL('%s IN %s', partner_expr, tuple(partner_ids)))
if 'partner_ledger_expand_partner' in options:
query.add_where(SQL('%s = %s', partner_expr, options['partner_ledger_expand_partner']))
rows = self.env.execute_query_dict(query.select(
SQL('%s AS grouping_key', groupby_expr),
SQL('SUM(%s) AS balance_delta', self._get_expr('balance', query)),
))
return {row['grouping_key']: row['balance_delta'] for row in rows if row['balance_delta']}
@api.model
def _get_expr(self, subformula, query):
expr = SQL('NULL')
rules = self._get_subformulas_rules().get(subformula, {})
field_name = rules.get('field', subformula)
field = self.env['account.move.line']._fields.get(field_name)
if to_sql := rules.get('to_sql'):
expr = to_sql(query)
elif field:
expr = query.table[field_name]
if field_name in FIELDS_TAKEN_FROM_PARTIALS:
expr = SQL('COALESCE(partials_data.%s, %s)', SQL.identifier(field_name), expr)
if field.type == 'monetary' and field.get_currency_field(self.env['account.move.line']) == 'company_currency_id':
expr = SQL("%s * %s", expr, query.table.consolidation_rate)
return expr
@api.model
def _get_agg_expr(self, subformula, query, groupbys, date_from):
if subformula.startswith('_currency_'):
return SQL(
"ARRAY_AGG(DISTINCT %s)",
query.table.currency_id,
)
expr = self._get_expr(subformula, query)
rules = self._get_subformulas_rules().get(subformula, {})
field_name = rules.get('field', subformula)
field = self.env['account.move.line']._fields.get(field_name)
from_beginning = rules.get('from_beginning') or (rules.get('cumulative_sum') and groupbys and groupbys[-1] == 'id')
if not from_beginning and date_from:
expr = SQL("""
CASE
WHEN %(date_field)s >= %(date_from)s THEN %(expr)s
ELSE NULL
END
""",
date_field=self._get_expr('invoice_date', query),
date_from=date_from,
expr=expr,
)
if field and field.type in {'integer', 'float', 'monetary'}:
if field.get_currency_field(self.env['account.move.line']) != 'company_currency_id':
expr = SQL(
"""
CASE
-- Small optimization to count distinct currencies on large datasets.
-- If both MIN() and MAX() are equal, it means there's only one 'currency_id'.
WHEN MIN(%(currency_expr)s) = MAX(%(currency_expr)s) AND MIN(%(currency_expr)s) != %(company_currency_id)s
AND ABS(SUM(%(expr)s)) > 0.01
THEN SUM(%(expr)s)
ELSE NULL
END
""",
currency_expr=query.table.currency_id,
expr=expr,
company_currency_id=self.env.company.currency_id.id,
)
else:
expr = SQL('SUM(%s)', expr)
if from_beginning and date_from:
query.having = SQL('%s OR %s', query.having, SQL('%s != 0', expr))
if rules.get('cumulative_sum') and groupbys and groupbys[-1] == 'id':
return SQL(
'SUM (%s) OVER (PARTITION BY %s ORDER BY %s)',
expr, SQL(', ').join(self._get_expr(groupby, query) for groupby in groupbys[:-1]), query.order,
)
return expr
if not groupbys or groupbys[-1] != 'id':
return SQL('NULL')
if field and field.type == 'boolean':
return SQL('BOOL_AND(%s)', expr)
return SQL('MIN(%s)', expr)
@api.model
def _get_aggregated_lines(self, subformulas, options, groupbys, date_scope):
report = self.env['account.report'].browse(options['report_id'])
date_from, _date_to = report._get_date_bounds_info(options, None)
if date_scope != 'from_beginning':
# The query itself is bounded to the evaluated period; no need to emulate the period bounds in SQL.
date_from = None
query = self._get_partner_ledger_query(options, date_scope=date_scope)
if date_from:
query.having = SQL('MAX(account_move_line.date) >= %s', date_from)
groupby_exprs = [self._get_expr(groupby, query) for groupby in groupbys]
query.groupby = SQL(', ').join(groupby_exprs)
return self.env.execute_query_dict(query.select(
*[SQL('%s AS %s', groupby_expr, SQL.identifier(groupby)) for groupby_expr, groupby in zip(groupby_exprs, groupbys)],
*[SQL('%s AS %s', self._get_agg_expr(subformula, query, groupbys, date_from), SQL.identifier(subformula)) for subformula in subformulas],
))
@api.model
def _get_move_lines(self, subformulas, options, groupbys, date_scope):
report = self.env['account.report'].browse(options['report_id'])
date_from, _date_to = report._get_date_bounds_info(options, None)
query = self._get_partner_ledger_query(options, date_scope)
if date_from:
id_expr = SQL("""
CASE
WHEN %(date_field)s >= %(date_from)s THEN %(expr)s
ELSE NULL
END
""",
date_field=self._get_expr('invoice_date', query),
date_from=date_from,
expr=self._get_expr('id', query),
)
else:
id_expr = self._get_expr('id', query)
previous_groupbys_exprs = [self._get_expr(groupby, query) for groupby in groupbys[:-1]]
query.groupby = SQL(', ').join([*previous_groupbys_exprs, id_expr])
query.having = SQL('%s != 0', id_expr) if date_from else SQL()
order_clause = [
*previous_groupbys_exprs,
*self._get_date_order_clause(query, groupbys, date_from),
id_expr,
]
query.order = SQL(', ').join(order_clause)
return self.env.execute_query_dict(query.select(
SQL('%s AS id', id_expr),
*[SQL('%s AS %s', groupby_expr, SQL.identifier(groupby)) for groupby_expr, groupby in zip(previous_groupbys_exprs, groupbys[:-1])],
*[SQL('%s AS %s', self._get_agg_expr(subformula, query, groupbys, date_from), SQL.identifier(subformula)) for subformula in subformulas],
))
@api.model
def _get_date_order_clause(self, query, groupbys, date_from):
return [SQL('%s ASC NULLS FIRST', self._get_agg_expr('invoice_date', query, groupbys, date_from))]
####################################################
# HELPERS
####################################################
@api.model
def _get_partner_ledger_query(self, options, date_scope, match_partner_on_partials=True):
report = self.env['account.report'].browse(options['report_id'])
if match_partner_on_partials and (partner_ids := options.get('partner_ids')):
# This is necessary for the query to consider lines without partner that are reconciled with a line having a partner.
# It is controlled through a parameter to give more control on this to variants not needing that behavior, since it's more
# efficient index-wise to rely on the move lines' partner_id field directly, as _get_options_domain does by default.
query = report._get_report_query({**options, 'partner_ids': []}, date_scope)
if partner_ids:
query.add_where(SQL('%s IN %s', self._get_expr('partner_id', query), tuple(partner_ids)))
else:
query = report._get_report_query(options, date_scope)
if 'partner_ledger_expand_partner' in options:
partner_expr = self._get_expr('partner_id', query)
partner_id = options['partner_ledger_expand_partner']
query.add_where(SQL('%s = %s', partner_expr, partner_id) if partner_id else SQL('%s IS NULL', partner_expr))
self._add_partials_data_join(query)
return query
@api.model
def _add_partials_data_join(self, query):
""" Joins the partial reconciliations of the move lines without partner that are reconciled with a line having one"""
query.add_join(
kind='LEFT JOIN LATERAL',
alias='partials_data',
table=SQL("""(
SELECT NULL::INTEGER AS id,
NULL::INTEGER AS partner_id,
NULL::NUMERIC AS debit,
NULL::NUMERIC AS credit,
NULL::NUMERIC AS amount_currency,
NULL::NUMERIC AS balance
UNION ALL
SELECT account_move_line.id AS id,
credit_line_with_partner.partner_id AS partner_id,
apr.amount AS debit,
0 AS credit,
apr.debit_amount_currency AS amount_currency,
apr.amount AS balance
FROM account_partial_reconcile apr
JOIN account_move_line credit_line_with_partner ON (apr.debit_move_id = account_move_line.id AND apr.credit_move_id = credit_line_with_partner.id)
WHERE account_move_line.partner_id IS NULL
AND credit_line_with_partner.partner_id IS NOT NULL
UNION ALL
SELECT -account_move_line.id AS id,
NULL AS partner_id,
0 AS debit,
apr.amount AS credit,
-apr.debit_amount_currency AS amount_currency,
-apr.amount AS balance
FROM account_partial_reconcile apr
JOIN account_move_line credit_line_with_partner ON (apr.debit_move_id = account_move_line.id AND apr.credit_move_id = credit_line_with_partner.id)
WHERE account_move_line.partner_id IS NULL
AND credit_line_with_partner.partner_id IS NOT NULL
UNION ALL
SELECT account_move_line.id AS id,
debit_line_with_partner.partner_id AS partner_id,
0 AS debit,
apr.amount AS credit,
-apr.credit_amount_currency AS amount_currency,
-apr.amount AS balance
FROM account_partial_reconcile apr
JOIN account_move_line debit_line_with_partner ON (apr.debit_move_id = debit_line_with_partner.id AND apr.credit_move_id = account_move_line.id)
WHERE account_move_line.partner_id IS NULL
AND debit_line_with_partner.partner_id IS NOT NULL
UNION ALL
SELECT -account_move_line.id AS id,
NULL AS partner_id,
apr.amount AS debit,
0 AS credit,
apr.credit_amount_currency AS amount_currency,
apr.amount AS balance
FROM account_partial_reconcile apr
JOIN account_move_line debit_line_with_partner ON (apr.debit_move_id = debit_line_with_partner.id AND apr.credit_move_id = account_move_line.id)
WHERE account_move_line.partner_id IS NULL
AND debit_line_with_partner.partner_id IS NOT NULL
)"""),
condition=SQL('TRUE'),
)
####################################################
# MISC
####################################################
@api.model
def _get_report_send_recipients(self, options):
partners = options.get('partner_ids', [])
if not partners:
rows = self._get_aggregated_lines([], options, ['partner_id'], 'from_beginning')
partners = [row['partner_id'] for row in rows]
return self.env['res.partner'].browse(partner for partner in partners if partner)
####################################################
# ACTIONS
####################################################
@api.model
def action_open_partner(self, options, params):
_model, record_id = self.env['account.report']._get_model_info_from_id(params['id'])
return {
'type': 'ir.actions.act_window',
'res_model': 'res.partner',
'res_id': record_id,
'views': [[False, 'form']],
'view_mode': 'form',
'target': 'current',
}
@api.model
def open_journal_items(self, options, params):
params['view_ref'] = 'account.view_move_line_tree_grouped_partner'
report = self.env['account.report'].browse(options['report_id'])
if report._get_option_recon_date(options):
params['view_ref'] = 'account.view_move_line_tree_open_on'
action = report.open_journal_items(options=options, params=params)
action.get('context', {}).update({'search_default_group_by_account': 0})
return action
@api.model
def caret_option_open_record_form_custom_id_groupby(self, options, params):
""" Copy-pasted from general ledger
"""
report = self.env['account.report'].browse(options['report_id'])
_model, aml_key = report._get_model_info_from_id(params['line_id'])
record = self.env['account.move.line'].browse(int(aml_key))
target_record = record[params['action_param']] if 'action_param' in params else record
view_id = report._resolve_caret_option_view(target_record)
action = {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(view_id, 'form')], # view_id will be False in case the default view is needed
'res_model': target_record._name,
'res_id': target_record.id,
'context': self.env.context,
}
if view_id is not None:
action['view_id'] = view_id
return action
@api.model
def action_toggle_no_followup(self, line_id, all_line_ids):
"""Toggle the `no_followup` field on the journal item corresponding to the given `line_id`.
Toggling this field may result in other journal items of the same report having their field toggled as well.
This function will return all impacted lines, so the report can be updated dynamically.
:param line_id: The report line ID.
:param all_line_ids: A list containing all the report's line IDs.
:return: A dict containing:
- `updated_value`: the updated `no_followup` value (`True` or `False`)
- `updated_line_ids`: a list of the impacted report lines
"""
model, aml_id = self.env['account.report']._get_model_info_from_id(line_id)
if model is not None or not aml_id:
return None
aml = self.env['account.move.line'].browse(int(aml_id))
aml.no_followup = not aml.no_followup
aml_id_to_line_id = {}
for cur_line_id in all_line_ids:
model, record_id = self.env['account.report']._get_model_info_from_id(cur_line_id)
if model is None and record_id:
aml_id_to_line_id[int(record_id)] = cur_line_id
res = {'updated_value': aml.no_followup, 'updated_line_ids': [aml_id_to_line_id[aml.id]]}
move = aml.move_id
if move.is_invoice():
# For invoices, the `no_followup` toggle will impact all its receivable/payable lines.
res['updated_line_ids'] = move.line_ids.filtered(
lambda line: line.account_type in ('asset_receivable', 'liability_payable') and line.id in aml_id_to_line_id,
).mapped(lambda line: aml_id_to_line_id[line.id])
return res

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,518 @@
import json
from collections import deque
from datetime import date
from odoo import api, models, fields
from odoo.exceptions import UserError
from odoo.fields import Domain
from odoo.tools import SQL
SNAPSHOTABLE_ENGINES = {}
def snapshotable_engine(result_aggregators, sub_engine_of=None, version=1):
""" Decorator to be used on engine functions to mark them as able to use account.report.snapshot objects in their computation.
When an engine is snapshotable, each call to it will search for a snapshot covering the desired period. If the covering is full, the result
from the snapshot will directly be used, and no report query will be run at all. If it is partial, a call to the engine will be made, forcing
the considered period to only consist of the gap between the snapshot and what we want to compute. The result of this call will then be combined
with the snapshot's result, hence forming the global result for this engine call. This also works in multi-company, where each company can
have its own snapshots, at different dates.
Note that any report engine cannot be made snapshotable. To be snapshotable, an engine must be composable: it must be possible to compute it by
part (we call those parts result partitions). Merging the different parts must give the exact same result as computing the full period directly.
The engine must allow being split like that by company and date.
Another important point is warnings won't be kept by snapshots. So, only the actual calls to the engine will generate them. This is considered
acceptable, since snapshots are generated for locked periods, and it's unlikely the data in such periods require any kind of warning.
This decorator can be used on both standard and custom engines.
"""
def decorator(engine_func):
engine_main_func_name = sub_engine_of or engine_func.__name__
def snapshotable_engine_wrapper(self, options, date_scope, formulas_dict, groupby, warnings=None):
# For custom engines, 'self' is the custom handler, not the report.
report = self if self._name == 'account.report' else self.env['account.report'].browse(options['report_id'])
if not report.enable_snapshots:
return engine_func(self, options, date_scope, formulas_dict, groupby, warnings=warnings)
snapshots = report.env['account.report.snapshot']._get_latest_snapshots(engine_main_func_name, version, options, date_scope, formulas_dict, groupby)
snapshot_domain = None
need_to_call_engine = True
if len(set(snapshots.mapped('date'))) == 1 and len(snapshots) == len(options['companies']):
if fields.Date.to_string(snapshots[0].date) != report._get_date_bounds_info(options, date_scope)[1]:
snapshot_domain = [('date', '>', snapshots[0].date)]
else:
# We don't want to call the engine at all: the snapshots already cover everything
need_to_call_engine = False
elif snapshots:
snapshot_domain_terms = []
for snapshot in snapshots:
snapshot_domain_terms.append([('company_id', '=', snapshot.company_id.id), ('date', '>', snapshot.date)])
company_ids_without_snapshot = set(report.env['account.report'].get_report_company_ids(options)) - set(snapshots.mapped('company_id').ids)
if company_ids_without_snapshot:
snapshot_domain_terms.append([('company_id', 'in', tuple(company_ids_without_snapshot))])
snapshot_domain = Domain.OR(snapshot_domain_terms)
result_partitions = snapshots._read_result_partitions()
if need_to_call_engine:
if snapshot_domain:
options = {
**options,
'forced_domain': list(Domain.AND([options.get('forced_domain', []), snapshot_domain])),
}
result_partitions.append(engine_func(self, options, date_scope, formulas_dict, groupby, warnings=warnings))
return report.env['account.report.snapshot']._merge_result_partitions(result_partitions, result_aggregators)
snapshotable_engine_data = {'version': version, 'result_aggregators': result_aggregators}
if sub_engine_of:
snapshotable_engine_data['sub_engine'] = engine_func.__name__
SNAPSHOTABLE_ENGINES[engine_main_func_name] = snapshotable_engine_data
return snapshotable_engine_wrapper
return decorator
class AccountReportSnapshot(models.Model):
_name = 'account.report.snapshot'
_description = "Accounting Report Snapshot"
report_id = fields.Many2one(comodel_name='account.report', required=True, index='btree')
engine_func = fields.Char(required=True)
engine_version = fields.Integer(required=True)
serialized_options = fields.Json(required=True)
serialized_formulas_dict = fields.Json(required=True)
date_scope = fields.Char(required=True)
company_id = fields.Many2one(comodel_name='res.company', required=True)
date = fields.Date(required=True)
groupby = fields.Char()
result = fields.Json(required=True)
_unique = models.Constraint(
"UNIQUE(serialized_options, serialized_formulas_dict, engine_func, engine_version, date_scope, company_id, report_id, date, groupby)",
"You cannot create duplicate report snapshots for the same company, report and date with the same engine parameters.",
)
def _register_hook(self):
rslt = super()._register_hook()
# Clean snapshots made for previous versions of the engines, and trigger the snapshot cron if necessary.
# With this, we can ensure a fix made in stable in the computation of an engine will trigger the proper recomputation of the snapshots
outdated_snapshots_domains = []
for engine_func_name, engine_info in SNAPSHOTABLE_ENGINES.items():
outdated_snapshots_domains.append([
('engine_func', '=', engine_func_name),
('engine_version', '<', engine_info['version']),
])
outdated_snapshots = self.env['account.report.snapshot'].search(Domain.OR(outdated_snapshots_domains))
outdated_snapshots.unlink()
if outdated_snapshots:
self.env.ref('account_reports.ir_cron_create_snapshots')._trigger()
return rslt
@api.model
def _cron_create_snapshots(self):
all_snapshots_to_create_params = self._get_snapshots_to_create_params()
asked_creation_date = None
created_snapshot = None
for report, col_group_options, engine, date_scope, formulas_dict, groupby in all_snapshots_to_create_params:
asked_creation_date = fields.Date.from_string(col_group_options['date']['date_to'])
created_snapshot = self._make_snapshot(report, col_group_options, engine, date_scope, formulas_dict, groupby, years_spread=5)
if created_snapshot:
# The next ones will be run in a future execution of the cron
break
# If the iterator still has elements to treat, we possibly have more snapshots left to generate.
# If the created snapshot's date is not the one that was asked for, it means it was created in the past, because of years_spread. We then
# need to re-call the cron to fill the gap, until all required snapshots have been generated in the past.
if next(all_snapshots_to_create_params, None) or (created_snapshot and created_snapshot.date != asked_creation_date):
self.env.ref('account_reports.ir_cron_create_snapshots')._trigger()
return created_snapshot
@api.model
def _cron_garbage_collect_snapshots(self):
generic_tax_report = self.env.ref('account.generic_tax_report')
snapshot_deletion_domains = []
for company in self.env['res.company'].search([]).with_context(ignore_exceptions=True):
fy_hard_lock_date = max(company.user_fiscalyear_lock_date, company.user_hard_lock_date)
if fy_hard_lock_date != date.min:
snapshot_deletion_domains.append([
('date', '>', fy_hard_lock_date),
('company_id', '=', company.id),
('report_id.root_report_id', '!=', generic_tax_report.id),
])
if company.user_tax_lock_date != date.min:
snapshot_deletion_domains.append([
('date', '>', company.user_tax_lock_date),
('company_id', '=', company.id),
('report_id.root_report_id', '=', generic_tax_report.id),
])
self.env['account.lock_exception'].flush_model()
self.env.cr.execute(SQL("""
SELECT DISTINCT ON (company_id, lock_date_field)
company_id,
lock_date_field,
lock_date,
end_datetime
FROM account_lock_exception
WHERE
lock_date_field IN ('fiscalyear_lock_date', 'tax_lock_date')
ORDER BY company_id, lock_date_field, create_date
"""))
for (company_id, lock_date_field, lock_date, end_datetime) in self.env.cr.fetchall():
# For simplicity, we consider all branches are impacted, and need garbage collection of their snapshots, even if they have a more
# restrictive lock date themselves.
impacted_branches = self.env['res.company'].search([('id', 'child_of', company_id)])
exception_violation_domain = [('company_id', 'in', impacted_branches.ids)]
if lock_date:
exception_violation_domain.append(('date', '>', lock_date))
if end_datetime:
exception_violation_domain.append(('create_date', '<', end_datetime))
if lock_date_field == 'tax_lock_date':
exception_violation_domain.append(('report_id.root_report_id', '=', generic_tax_report.id))
snapshot_deletion_domains.append(exception_violation_domain)
snapshots_to_unlink = self.env['account.report.snapshot'].search(Domain.OR(snapshot_deletion_domains))
snapshots_to_unlink.unlink()
refresh_cron = self.env.ref('account_reports.ir_cron_create_snapshots')
if not self.env['ir.cron.trigger'].search([('cron_id', '=', refresh_cron.id)], limit=1):
# If no call is planned in the future (as it would be the case with lock date exceptions), trigger the refresh
refresh_cron._trigger()
@api.model
def _get_snapshots_to_create_params(self):
call_time = fields.Datetime.now()
reports_to_snapshot = self.env['account.report'].search([('enable_snapshots', '=', True)])
all_companies = self.env['res.company'].search([])
generic_tax_report = self.env.ref('account.generic_tax_report')
for report in reports_to_snapshot:
is_tax_report = (report.root_report_id or report) == generic_tax_report
expressions_by_evaluation_groupby = {}
for line in report.line_ids:
# None => line's own totals
evaluation_groupbys = {None}
if line.foldability == 'always_unfolded' and (line_groupby := line._get_groupby()):
# The first groupby level of an always unfolded line is evaluated on every rendering of the report,
# so it needs its own snapshots as well
evaluation_groupbys.add(line_groupby)
for evaluation_groupby in evaluation_groupbys:
expressions_by_evaluation_groupby.setdefault(evaluation_groupby, self.env['account.report.expression'])
expressions_by_evaluation_groupby[evaluation_groupby] += line.expression_ids
for company in all_companies.with_context(ignore_exceptions=True):
lock_date = company.user_tax_lock_date if is_tax_report else max(company.user_fiscalyear_lock_date, company.user_hard_lock_date)
if lock_date == date.min or not report._is_available_for(company):
continue
# Don't generate anything if a lock date exception is covering this period. When it expires, the exception will trigger a new call to the cron
exception = self.env['account.lock_exception'].search([
('company_id', 'in', company.parent_ids.ids),
('tax_lock_date' if is_tax_report else 'fiscalyear_lock_date', '<', lock_date),
'|', ('end_datetime', '=', False), ('end_datetime', '>', call_time),
], limit=1)
if exception:
continue
options = report.with_context(allowed_company_ids=company.ids).get_options({
'date': {'date_to': fields.Date.to_string(lock_date), 'period_type': 'custom'},
'no_report_reroute': True,
})
if self._snapshot_forbidden(options):
continue
for evaluation_groupby, expressions in expressions_by_evaluation_groupby.items():
for col_group_options in report._split_options_per_column_group(options).values():
grouped_formulas_by_engine = report._group_expression_formulas(col_group_options, expressions, groupby_to_expand=evaluation_groupby)
for engine, grouped_formulas in grouped_formulas_by_engine.items():
for (date_scope, groupby), formulas_dict in grouped_formulas.items():
if date_scope in ['from_beginning', 'to_beginning_of_fiscalyear', 'to_beginning_of_period']:
yield report, col_group_options, engine, date_scope, formulas_dict, groupby
@api.model
def _make_snapshot(self, report, col_group_options, engine, date_scope, formulas_dict, groupby, years_spread=0):
""" Tries creating an account.report.snapshot object for the provided report engine parameters.
If engine is not snapshotable or a snapshot already exists for those parameters, None will be returned. Else, a new snapshot will be created
and returned.
The years_spread parameter is used to make sure snapshots are spread homogenously through time, so that period comparison in reports can
benefit from them. When set to a non-zero value, it will change the period of the generated snapshot if the last snapshot (or the first aml
of the accounting if there was not snapshot) is more than one year before the date_to of the options. The chosen date will be maximum
years_spread years before the date_to, or 1 year after the last snapshot, if it was more recent than that. This option is especially useful
when regenerating snapshots after garbage-collection, for example because of a change in an engine version (probably coming from a bugfix).
"""
company_ids = report.get_report_company_ids(col_group_options)
company = self.env['res.company'].browse(company_ids)
if len(company) > 1:
raise UserError(self.env._("Snapshots of accounting reports should be made one company at a time."))
engine_main_func_name = report._get_engine_function_name(engine)
if engine_main_func_name not in SNAPSHOTABLE_ENGINES:
return None
# Aim the options to the lock date, so that the engine call is snapshotted up to it.
col_group_options = self._align_options_with_snapshot_date(report, col_group_options, date_scope, fields.Date.to_date(col_group_options['date']['date_to']))
snapshot_date = fields.Date.to_date(report._get_date_bounds_info(col_group_options, date_scope)[1])
latest_snapshot = self._get_latest_snapshots(engine_main_func_name, SNAPSHOTABLE_ENGINES[engine_main_func_name]['version'], col_group_options, date_scope, formulas_dict, groupby)
if latest_snapshot and latest_snapshot.date == snapshot_date:
return None
if years_spread:
next_snapshot_fy_end = None
if latest_snapshot:
next_snapshot_fy_end = fields.Date.add(company.compute_fiscalyear_dates(latest_snapshot.date)['date_to'], years=1)
else:
aml_data = self.env['account.move.line'].search_read([('company_id', '=', company_ids[0])], fields=['date'], order='date ASC', limit=1)
if aml_data:
next_snapshot_fy_end = company.compute_fiscalyear_dates(aml_data[0]['date'])['date_to']
if next_snapshot_fy_end and next_snapshot_fy_end < snapshot_date:
# Instead of creating the snapshot at the date to, we create after the last snapshot, or years_spread years ago, at the end of a fiscal
# year, if it's closer. Doing it that way ensures we keep comparisons working when regenerating snapshots. A more naive approach where
# we only regenerate a snapshot at the current lock date would have made all comparisons super slow.
years_before_fy_end = company.compute_fiscalyear_dates(fields.Date.subtract(snapshot_date, years=years_spread))['date_to']
scoped_date_to = max(years_before_fy_end, next_snapshot_fy_end)
col_group_options = self._align_options_with_snapshot_date(report, col_group_options, date_scope, scoped_date_to)
snapshot_date = fields.Date.to_date(report._get_date_bounds_info(col_group_options, date_scope)[1])
function_to_call = report._get_custom_report_function(SNAPSHOTABLE_ENGINES[engine_main_func_name].get('sub_engine', engine_main_func_name), 'engine')
engine_result = function_to_call(col_group_options, date_scope, formulas_dict, groupby)
json_friendly_engine_result = {
','.join(str(expr.id) for expr in expressions): formula_res
for expressions, formula_res in engine_result.items()
}
return self.env['account.report.snapshot'].create([{
'serialized_options': self._get_serializable_options(col_group_options),
'serialized_formulas_dict': self._get_serializable_formulas_dict(formulas_dict),
'engine_func': engine_main_func_name,
'engine_version': SNAPSHOTABLE_ENGINES[engine_main_func_name]['version'],
'date_scope': date_scope,
'result': json_friendly_engine_result,
'company_id': company_ids[0],
'report_id': report.id,
'date': snapshot_date,
'groupby': groupby,
}])
@api.model
def _align_options_with_snapshot_date(self, report, col_group_options, date_scope, snapshot_date):
""" Returns the options making date_scope evaluate the accounting up to snapshot_date. """
# The 'to_beginning_of_*' scopes stop right before the period (or fiscal year) of the options; aiming
# them at the day after covers snapshot_date.
if date_scope == 'to_beginning_of_period':
date_option = {**col_group_options['date'], 'date_from': fields.Date.to_string(fields.Date.add(snapshot_date, days=1))}
elif date_scope == 'to_beginning_of_fiscalyear':
date_option = {**col_group_options['date'], 'date_to': fields.Date.to_string(fields.Date.add(snapshot_date, days=1))}
else:
date_option = {**col_group_options['date'], 'date_to': fields.Date.to_string(snapshot_date)}
col_group_options = {**col_group_options, 'date': date_option}
return col_group_options
@api.model
def _get_serializable_options(self, options):
option_keys_to_remove = self._get_option_keys_to_remove_for_snapshot(options)
serializable_options = {
key: value
for key, value in options.items()
if key not in option_keys_to_remove
}
# For options containing multiple elements with a 'selected' flag, we only keep the selected ones, in case some were
# added between snapshots/evaluations.
for option_with_select_flag in ('journals', 'aml_ir_filters'):
serializable_options[option_with_select_flag] = [
option_part['id']
for option_part in serializable_options.get(option_with_select_flag, [])
if option_part['selected']
]
return serializable_options
@api.model
def _get_serializable_formulas_dict(self, formulas_dict):
return {
formula: sorted(expressions.ids)
for formula, expressions in formulas_dict.items()
}
@api.model
def _get_option_keys_to_remove_for_snapshot(self, options):
return {
'audit', 'available_horizontal_groups', 'available_tax_units', 'available_variants', 'buttons', 'column_groups', 'column_headers',
'column_percent_comparison', 'columns', 'companies', 'comparison', 'consolidation', 'date', 'display_hierarchy_filter', 'export_mode',
'filter_date', 'filters', 'forced_companies', 'growth_display', 'has_inactive_sections', 'has_inactive_variants', 'hide_0_lines',
'hierarchy', 'horizontal_split', 'integer_rounding', 'integer_rounding_enabled', 'journal_groups', 'multi_currency', 'name_journal_group',
'no_report_reroute', 'order_column', 'owner_column_group', 'readonly_query', 'report_id', 'report_title', 'rounding_unit',
'rounding_unit_names', 'search_bar', 'sections', 'sections_source_id', 'selected_partner_ids', 'selected_section_id', 'selected_variant_id',
'show_consolidation', 'show_debug_column', 'show_horizontal_group_total', 'show_last_annotations', 'unfold_all',
'unfolded_lines', 'user_groups', 'variants_source_id',
}
@api.model
def _snapshot_forbidden(self, options):
return any(options.get(opt_key) for opt_key in ['partner_categories', 'unreconciled', 'recon_date'])
def _get_latest_snapshots(self, engine_func_name, engine_version, options, date_scope, formulas_dict, groupby):
""" Retrieves the most recent snapshot for each company corresponding to these engine parameters.
"""
if self._snapshot_forbidden(options):
return self.env['account.report.snapshot']
report = self.env['account.report'].browse(options['report_id'])
scoped_date_to = report._get_date_bounds_info(options, date_scope)[1]
self.env['account.report.snapshot'].flush_model()
self.env.cr.execute(SQL(
"""
SELECT DISTINCT ON (company_id)
id
FROM account_report_snapshot
WHERE
report_id = %(report_id)s
AND company_id IN %(company_ids)s
AND date <= %(date_to)s
AND serialized_options = %(serialized_options)s::JSONB
AND serialized_formulas_dict = %(serialized_formulas_dict)s::JSONB
AND engine_func = %(engine_func)s
AND engine_version = %(engine_version)s
AND date_scope = %(date_scope)s
AND COALESCE(groupby, '') = COALESCE(%(groupby)s, '')
ORDER BY company_id, date DESC
""",
serialized_options=json.dumps(self._get_serializable_options(options)),
serialized_formulas_dict=json.dumps(self._get_serializable_formulas_dict(formulas_dict)),
engine_func=engine_func_name,
engine_version=engine_version,
date_scope=date_scope,
report_id=options['report_id'],
company_ids=tuple(self.env['account.report'].get_report_company_ids(options)),
date_to=scoped_date_to,
groupby=groupby,
))
return self.env['account.report.snapshot'].browse(query_res[0] for query_res in self.env.cr.fetchall())
def _read_result_partitions(self):
rslt = []
for record in self:
json_friendly_result = record.result
rslt.append({
self.env['account.report.expression'].browse(int(id_str) for id_str in expression_ids_str.split(',')): formula_res
for expression_ids_str, formula_res in json_friendly_result.items()
})
return rslt
@api.model
def _merge_result_partitions(self, result_partitions, result_aggregators):
def _merge_individual_res_dict(existing_res, new_res):
for key, new_value in new_res.items():
aggregator = result_aggregators.get(key)
existing_value = existing_res[key]
if not aggregator:
raise Exception(self.env._(
"Trying to merge engine results values without aggregator: %(new_value)s and %(existing_value)s (key: %(key)s)",
new_value=new_value,
key=key,
existing_value=existing_value,
))
existing_res[key] = aggregator((existing_value, new_value))
def grouping_key_sort_key(group_entry):
# Keys can be mixed types (e.g., None for missing partners, strings, tuples).
# Bucket them by type to prevent sorting errors.
grouping_key = group_entry[0]
if grouping_key is None:
return (0, '')
if isinstance(grouping_key, (tuple, list)):
return (3, tuple(grouping_key_sort_key((sub_key,)) for sub_key in grouping_key))
if isinstance(grouping_key, str):
return (2, grouping_key)
return (1, grouping_key)
def _merge_sorted_lists(existing_list, new_list):
# Ordered merge of the two sorted lists, aggregating the entries sharing the same grouping key
merged_list = []
existing_deque = deque(existing_list)
new_deque = deque(new_list)
while existing_deque and new_deque:
existing_group_key, existing_group_res = existing_deque[0]
new_group_key, new_group_res = new_deque[0]
if existing_group_key == new_group_key:
_merge_individual_res_dict(existing_group_res, new_group_res)
merged_list.append(existing_deque.popleft())
new_deque.popleft()
elif grouping_key_sort_key(new_deque[0]) < grouping_key_sort_key(existing_deque[0]):
merged_list.append(new_deque.popleft())
else:
merged_list.append(existing_deque.popleft())
merged_list.extend(existing_deque)
merged_list.extend(new_deque)
return merged_list
rslt = {}
for partition in result_partitions:
for key, formula_rslt in partition.items():
if isinstance(formula_rslt, list):
formula_rslt.sort(key=grouping_key_sort_key) # Sort on the grouping keys, to help merging groupby results
existing_result = rslt.get(key)
if existing_result:
assert isinstance(existing_result, (dict, list))
if isinstance(existing_result, dict):
assert isinstance(formula_rslt, dict)
else:
assert isinstance(formula_rslt, list)
if isinstance(formula_rslt, list):
rslt[key] = _merge_sorted_lists(existing_result, formula_rslt)
elif isinstance(formula_rslt, dict):
_merge_individual_res_dict(existing_result, formula_rslt)
else:
raise Exception(self.env._("Wrong engine result format when merging snapshots."))
else:
rslt[key] = formula_rslt
return rslt

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,546 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from json import dumps, loads
from odoo import api, fields, models
from odoo.tools import SQL
from odoo.fields import Domain
class AccountEcSalesReportHandlerCommon(models.AbstractModel):
"""
EC Sales Report defining common functions for both the generic (taxes) and
localization specific (tax tags) custom handlers
Localizations-specific EC sales reports should not inherit this model,
but rather the one below: account.ec.sales.with.tags.report.handler
"""
_name = 'account.ec.sales.report.handler.common'
_inherit = ['account.report.custom.handler']
_description = 'Common EC Sales Report Handler'
def _custom_options_initializer(self, report, options, previous_options):
options['enable_export_buttons_for_common_vat_in_branches'] = True
options['custom_display_config'] = {
'components': {
'AccountReportFilters': 'SalesReportFilters',
},
}
@api.model
def _get_ec_country_codes(self, options):
"""
Return the list of country codes for the EC countries.
:param dict options: Report options
:return set: List of country codes for a given date (UK case)
"""
rslt = {'AT', 'BE', 'BG', 'HR', 'CY', 'CZ', 'DK', 'EE', 'FI', 'FR', 'DE', 'GR', 'HU',
'IE', 'IT', 'LV', 'LT', 'LU', 'MT', 'NL', 'PL', 'PT', 'RO', 'SK', 'SI', 'ES', 'SE', 'XI'}
# GB left the EU on January 1st 2021. But before this date, it's still to be considered as a EC country
if fields.Date.from_string(options['date']['date_from']) < fields.Date.from_string('2021-01-01'):
rslt.add('GB')
# Monaco is treated as part of France for VAT purposes (but should not be displayed within FR context)
if self.env.company.account_fiscal_country_id.code != 'FR':
rslt.add('MC')
return rslt
def _get_partner_details_query(self, current_groupby):
if current_groupby in ('partner_id', 'partner_id_and_sale_type'):
return SQL("""
MIN(partner.id) AS partner_id,
MIN(partner.name) AS partner_name,
MIN(CASE
WHEN LEFT(partner.vat, 2) SIMILAR TO '[A-Za-z]{2}' THEN UPPER(LEFT(partner.vat, 2))
ELSE UPPER(COALESCE(country.code, ''))
END) AS country_code,
MIN(partner.vat) AS vat_number,
""")
return SQL("""
'' AS partner_id,
'' AS partner_name,
'' AS country_code,
'' AS vat_number,
""")
def _format_vat_number(self, full_vat_number):
"""Format VAT number by removing country code if present."""
if not full_vat_number:
return ''
has_country_prefix = len(full_vat_number) >= 2 and full_vat_number[:2].isalpha()
return full_vat_number[2:] if has_country_prefix else full_vat_number
def _get_duplicate_vat_partners(self, duplicate_partners_vat):
view_ref = self.env.ref('account_reports.duplicate_vat_partner_tree_view', raise_if_not_found=False)
return {
'type': 'ir.actions.act_window',
'name': self.env._('Partners with duplicate VAT numbers'),
'context': {'group_by': 'vat', 'expand': 1, 'duplicate_partners_vat': duplicate_partners_vat},
'views': [(view_ref and view_ref.id or False, 'list'), (False, 'form')],
'res_model': 'res.partner',
'domain': [('vat', 'in', duplicate_partners_vat)],
}
@api.model
def _get_ec_sales_tax_tags(self):
""" To override in localizations
Should contain the sales types as keys, with a list of account tags as values
"""
return {}
class AccountEcSalesWithTaxesReportHandler(models.AbstractModel):
""" Generic EC Sales Report handler
Localization-specific EC sales reports should not inherit this handler,
but rather the one below: AccountEcSalesReportHandlerUsingTags
"""
_name = 'account.ec.sales.with.taxes.report.handler'
_inherit = ['account.ec.sales.report.handler.common']
_description = 'EC Sales Report (with taxes) Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
country_ids = self.env['res.country'].search([
('code', 'in', tuple(self._get_ec_country_codes(options)))
]).ids
other_country_ids = tuple(set(country_ids) - {self.env.company.account_fiscal_country_id.id})
options.setdefault('forced_domain', []).extend([
'|',
('move_id.partner_shipping_id.country_id', 'in', other_country_ids),
'&',
('move_id.partner_shipping_id', '=', False),
('partner_id.country_id', 'in', other_country_ids),
])
eu_countries = self.env.ref('base.europe').country_ids
ec_sales_taxes_to_include = self.env['account.tax'].search([
*self.env['account.tax']._check_company_domain(report.get_report_company_ids(options)),
('amount', '=', 0.0),
('amount_type', '=', 'percent'),
('type_tax_use', '=', 'sale'),
('country_id', 'in', eu_countries.ids),
]).ids
options['ec_sales_taxes_to_include'] = ec_sales_taxes_to_include
def _report_engine_ec_sales_report(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
""" Custom engine for EC Sales Report """
report = self.env['account.report'].browse(options['report_id'])
report_query = report._get_report_query(options, 'strict_range')
if current_groupby:
report._check_groupby_fields([current_groupby])
groupby_sql = SQL('') if not current_groupby else self.env['account.move.line']._field_to_sql("account_move_line", current_groupby, report_query)
ec_sales_taxes_to_include = tuple(options['ec_sales_taxes_to_include']) or (None,)
if not ec_sales_taxes_to_include and warnings is not None:
warnings['account_reports.sales_report_warning_no_taxes_to_include'] = {'alert_type': 'warning'}
query = SQL(
"""
SELECT
%(grouping_key)s
%(partner_details)s
COALESCE(-SUM(%(balance)s), 0.0) AS balance
FROM
%(from_clause)s
LEFT JOIN res_partner partner ON partner.id = account_move_line.partner_id
JOIN res_country country ON partner.country_id = country.id
WHERE
%(where_clause)s
AND EXISTS (
SELECT 1
FROM account_move_line_account_tax_rel aml_tax_rel
WHERE aml_tax_rel.account_move_line_id = account_move_line.id
AND aml_tax_rel.account_tax_id IN %(ec_sales_taxes_to_include)s
LIMIT 1
)
%(group_by_sql)s
%(order_by_sql)s
""",
ec_sales_taxes_to_include=ec_sales_taxes_to_include,
grouping_key=SQL('%s AS grouping_key,', groupby_sql) if groupby_sql else SQL(),
partner_details=self._get_partner_details_query(current_groupby),
balance=report_query.table.consolidation_balance,
from_clause=report_query.from_clause,
where_clause=report_query.where_clause,
group_by_sql=SQL('GROUP BY %s', groupby_sql) if groupby_sql else SQL(),
order_by_sql=SQL('ORDER BY %s', groupby_sql) if groupby_sql else SQL(),
)
self.env.cr.execute(query)
query_res_lines = self.env.cr.dictfetchall()
# Post-process values
for res in query_res_lines:
if res['vat_number']:
res['vat_number'] = self._format_vat_number(res['vat_number'])
if not current_groupby:
return {next(iter(formulas_dict.values())): {
'country_code': '',
'vat_number': '',
'balance': query_res_lines[0]['balance'],
'has_sublines': True,
}}
else:
return {next(iter(formulas_dict.values())): [
(res['grouping_key'],
{
'country_code': res['country_code'],
'vat_number': res['vat_number'],
'balance': res['balance'],
'has_sublines': True,
})
for res in query_res_lines
]}
class AccountEcSalesWithTagsReportHandler(models.AbstractModel):
_name = 'account.ec.sales.with.tags.report.handler'
_inherit = ['account.ec.sales.report.handler.common']
_description = 'EC Sales Report (with tags) Custom Handler'
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
options['sales_report_operation_types'] = options.get('sales_report_operation_types') or previous_options.get('sales_report_operation_types', {})
# Add filter for sale type (only for reports using the custom groupby)
if report.line_ids.filtered(lambda l: l._get_groupby(options) == 'partner_id_and_sale_type'):
# Filter on Tax Code
filter_sale_type_selection = [
{
'id': sale_type_key,
'name': sale_type_val['name'],
'selected': True,
}
for sale_type_key, sale_type_val in options['sales_report_operation_types'].items()
]
options['filter_sale_type_selection'] = previous_options.get('filter_sale_type_selection') or filter_sale_type_selection
# If none are selected, select them all
if all(not item['selected'] for item in options['filter_sale_type_selection']):
for item in options['filter_sale_type_selection']:
item['selected'] = True
def _report_engine_ec_sales_report(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
""" Custom engine for EC Sales Report """
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
report_query = report._get_report_query(options, 'strict_range')
groupby_sql = (
SQL() if not current_groupby
else SQL('partner.id, sale_type') if current_groupby == 'partner_id_and_sale_type'
else self.env['account.move.line']._field_to_sql('account_move_line', current_groupby, report_query)
)
sum_by_sale_type = SQL(' ').join([
SQL(
"""
COALESCE(SUM(
CASE WHEN aml_id_sale_type.sale_type = %(sale_type)s
THEN -%(balance)s ELSE 0 END
), 0) AS %(sale_type_alias)s,
""",
sale_type=sale_type,
sale_type_alias=SQL.identifier(sale_type),
balance=report_query.table.consolidation_balance,
)
for sale_type in options['sales_report_operation_types']
])
ec_sales_warnings = SQL("""
BOOL_OR(partner.vat IS NULL) AS warning_missing_vat,
BOOL_OR(
(
delivery_country.code IS NULL
AND UPPER(COALESCE(country.code, '')) NOT IN %(ec_country_codes)s
)
OR (
delivery_country.code IS NOT NULL
AND UPPER(delivery_country.code) NOT IN %(ec_country_codes)s
)
) AS warning_non_ec_country,
BOOL_OR(
(
delivery_address.country_id IS NULL
AND partner.country_id = comp_partner.country_id
)
OR (
delivery_address.country_id IS NOT NULL
AND delivery_address.country_id = comp_partner.country_id
)
) AS warning_same_country,
""",
ec_country_codes=tuple(self._get_ec_country_codes(options)) + ('',)
) if warnings is not None else SQL()
query = SQL(
"""
WITH aml_id_sale_type AS (
SELECT DISTINCT
account_account_tag_account_move_line_rel.account_move_line_id,
CASE %(sale_type_statements)s ELSE '' END AS sale_type
FROM account_account_tag_account_move_line_rel
JOIN account_account_tag ON account_account_tag_account_move_line_rel.account_account_tag_id = account_account_tag.id
WHERE CASE %(sale_type_statements)s ELSE NULL END IS NOT NULL
)
SELECT
%(grouping_key)s
%(partner_details)s
%(sum_by_sale_type)s
%(sale_type)s
%(warnings)s
COALESCE(-SUM(%(balance)s), 0.0) AS balance
FROM
%(from_clause)s
LEFT JOIN res_partner partner ON partner.id = account_move_line.partner_id
JOIN aml_id_sale_type ON aml_id_sale_type.account_move_line_id = account_move_line.id
JOIN res_country country ON partner.country_id = country.id
JOIN res_company ON res_company.id = account_move_line.company_id
JOIN res_partner comp_partner ON comp_partner.id = res_company.partner_id
JOIN account_move ON account_move.id = account_move_line.move_id
LEFT JOIN res_partner delivery_address ON account_move.partner_shipping_id = delivery_address.id
LEFT JOIN res_country delivery_country ON delivery_address.country_id = delivery_country.id
WHERE %(where_clause)s
%(groupby_clause)s
%(orderby_clause)s
""",
sale_type_statements=self._build_sale_type_statements(options),
grouping_key=SQL('%s AS grouping_key,', groupby_sql or ''),
partner_details=self._get_partner_details_query(current_groupby),
sum_by_sale_type=sum_by_sale_type,
sale_type=SQL("%s AS sale_type,", SQL("MIN(aml_id_sale_type.sale_type)") if current_groupby == 'partner_id_and_sale_type' else ''),
warnings=ec_sales_warnings,
balance=report_query.table.consolidation_balance,
from_clause=report_query.from_clause,
where_clause=report_query.where_clause,
groupby_clause=SQL('GROUP BY %s', groupby_sql) if groupby_sql else SQL(),
orderby_clause=SQL('ORDER BY %s', groupby_sql) if groupby_sql else SQL(),
)
self.env.cr.execute(query)
query_res_lines = self.env.cr.dictfetchall()
if not current_groupby:
if warnings is not None:
for key, value in query_res_lines[0].items():
if key.startswith('warning') and value:
warning_key = f'account_reports.sales_report_{key}'
warnings[warning_key] = {'alert_type': 'warning'}
return {next(iter(formulas_dict.values())): {
'country_code': '',
'vat_number': '',
'sale_type': '',
'sale_type_name': '',
'sale_type_shortcut': '',
'balance': query_res_lines[0]['balance'],
'has_sublines': True,
**{
sale_type: query_res_lines[0].get(sale_type, '') if query_res_lines else ''
for sale_type in options['sales_report_operation_types']
}
}}
results = []
for res in query_res_lines:
# Define grouping key
if current_groupby == 'partner_id_and_sale_type':
grouping_keys = ('partner_id', 'sale_type')
grouping_key = {key: res[key] for key in grouping_keys}
grouping_key['tax_tag_ids'] = options['sales_report_operation_types'][res['sale_type']]['tax_tag_ids']
grouping_key = dumps(grouping_key)
else:
grouping_key = res['grouping_key']
# Post-process values
if res['vat_number']:
res['vat_number'] = self._format_vat_number(res['vat_number'])
sale_type = res['sale_type']
if sale_type and options['sales_report_operation_types'][sale_type].get('name'):
res['sale_type_name'] = options['sales_report_operation_types'][sale_type]['name']
if sale_type and options['sales_report_operation_types'][sale_type].get('shortcut'):
res['sale_type_shortcut'] = options['sales_report_operation_types'][sale_type]['shortcut']
results.append(
(grouping_key,
{
'country_code': res['country_code'],
'vat_number': res['vat_number'],
'sale_type': res['sale_type'],
'sale_type_name': res.get('sale_type_name', ''),
'sale_type_shortcut': res.get('sale_type_shortcut', ''),
'balance': res['balance'],
'has_sublines': True,
**{
sale_type: res.get(sale_type, '')
for sale_type in options['sales_report_operation_types']
}
})
)
return {next(iter(formulas_dict.values())): results}
def _build_sale_type_statements(self, options):
"""Build CASE statements for sale types."""
not_selected_filters = {item['id'] for item in options.get('filter_sale_type_selection', []) if not item['selected']}
return SQL(' ').join([
SQL(
"WHEN account_account_tag.id = ANY(%(tax_tag_ids)s) THEN %(sale_type)s",
tax_tag_ids=list(data['tax_tag_ids']),
sale_type=sale_type,
)
for sale_type, data in options['sales_report_operation_types'].items() if sale_type not in not_selected_filters
])
def action_audit_cell(self, options, params):
report_line = self.env['account.report.line'].browse(params['report_line_id'])
action = report_line.report_id.action_audit_cell(options, params)
tax_tag_ids = list({
tag
for sale_type in options['sales_report_operation_types'].values()
for tag in sale_type['tax_tag_ids']
})
action['domain'] &= Domain('tax_tag_ids', 'in', tax_tag_ids)
return action
def _get_custom_groupby_map(self):
def ec_sales_report_domain_builder(grouping_key):
grouping_key_dict = loads(grouping_key)
tax_tag_ids = grouping_key_dict['tax_tag_ids']
return Domain([
('partner_id', '=', grouping_key_dict['partner_id']),
('tax_tag_ids', 'in', tax_tag_ids),
])
def ec_sales_report_label_builder(grouping_keys):
parsed_keys = [loads(k) for k in grouping_keys]
partner_ids = [k['partner_id'] for k in parsed_keys]
partners = self.env['res.partner'].browse(partner_ids)
partner_names = {p.id: p.display_name for p in partners}
return {
grouping_key: partner_names[parsed['partner_id']]
for grouping_key, parsed in zip(grouping_keys, parsed_keys)
}
return {
"partner_id_and_sale_type": {
'model': None,
'domain_builder': ec_sales_report_domain_builder,
'label_builder': ec_sales_report_label_builder,
},
}
def _caret_options_initializer(self):
"""
Add custom caret option for the report to link to the partner.
"""
return {
'partner_id_and_sale_type': [
{'name': self.env._("View Partner"), 'action': 'caret_options_open_partner_record_form'},
],
}
def caret_options_open_partner_record_form(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
partner_id = loads(report._parse_line_id(params['line_id'])[-1][2])['partner_id']
return {
'type': 'ir.actions.act_window',
'view_mode': 'form',
'views': [(False, 'form')],
'res_model': 'res.partner',
'res_id': partner_id,
}
def _custom_groupby_line_completer(self, report, options, line_data, current_groupby):
if current_groupby == 'partner_id_and_sale_type':
line_data.caret_options = 'partner_id_and_sale_type'
def get_warning_act_window(self, options, params):
act_window = {'type': 'ir.actions.act_window', 'context': {}}
type_mapping = {
'no_vat': {
'aml_domain': [
('partner_id.vat', '=', None),
('partner_id.country_id.code', 'in', tuple(self._get_ec_country_codes(options))),
],
'name': self.env._("Entries with partners with no VAT"),
'context': {'search_default_group_by_partner': 1, 'expand': 1}
},
'non_ec_country': {
'aml_domain': [
'|',
'&',
('move_id.partner_shipping_id', '!=', False),
('move_id.partner_shipping_id.country_id.code', 'not in', tuple(self._get_ec_country_codes(options))),
'&',
('move_id.partner_shipping_id', '=', False),
('partner_id.country_id.code', 'not in', tuple(self._get_ec_country_codes(options)))
],
'name': self.env._("EC tax on non EC countries")
},
'same_country': {
'aml_domain': [
'|',
'&',
('move_id.partner_shipping_id', '!=', False),
('move_id.partner_shipping_id.country_id', '=', self.env.company.account_fiscal_country_id.id),
'&',
('move_id.partner_shipping_id', '=', False),
('partner_id.country_id', '=', self.env.company.account_fiscal_country_id.id)
],
'name': self.env._("EC tax on same country")
}
}
type_info = type_mapping.get(params['type'], {})
aml_domain = type_info.get('aml_domain', [])
act_window['name'] = type_info.get('name', '')
act_window['context'].update(type_info.get('context', {}))
not_allowed_sale_types = {sale_type['id'] for sale_type in options.get('filter_sale_type_selection', []) if not sale_type.get('selected', True)}
ec_sales_tag_ids = {
tag
for sale_type in options['sales_report_operation_types']
if sale_type not in not_allowed_sale_types
for tag in options['sales_report_operation_types'][sale_type]['tax_tag_ids']
}
amls = self.env['account.move.line'].search([
*aml_domain,
('parent_state', '=', 'posted'),
*self.env['account.report']._get_options_date_domain(options, 'strict_range'),
('tax_tag_ids', 'in', tuple(ec_sales_tag_ids))
])
if params['model'] == 'move':
act_window.update({
'views': [[self.env.ref('account.view_move_tree').id, 'list'], (False, 'form')],
'res_model': 'account.move',
'domain': [('id', 'in', amls.move_id.ids)],
})
else:
act_window.update({
'views': [(False, 'list'), (False, 'form')],
'res_model': 'res.partner',
'domain': [('id', 'in', amls.move_id.partner_id.ids)],
})
return act_window

View File

@@ -0,0 +1,162 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, models, fields, Command, _
from odoo.exceptions import ValidationError
class AccountTaxUnit(models.Model):
_name = 'account.tax.unit'
_description = "Tax Unit"
name = fields.Char(string="Name", required=True)
country_id = fields.Many2one(string="Country", comodel_name='res.country', required=True, inverse="_inverse_vat", help="The country in which this tax unit is used to group your companies' tax reports declaration.")
vat = fields.Char(string="Tax ID", required=True, inverse="_inverse_vat", help="The identifier to be used when submitting a report for this unit.")
company_ids = fields.Many2many(string="Companies", comodel_name='res.company', required=True, help="Members of this unit")
main_company_id = fields.Many2one(string="Main Company", comodel_name='res.company', required=True, help="Main company of this unit; the one actually reporting and paying the taxes.")
fpos_synced = fields.Boolean(string="Fiscal Positions Synchronised", compute='_compute_fiscal_position_completion', help="Technical field indicating whether Fiscal Positions exist for all companies in the unit")
@api.model_create_multi
def create(self, vals_list):
res = super().create(vals_list)
horizontal_groups = self.env['account.report.horizontal.group'].create([
{
'name': tax_unit.name,
'rule_ids': [
Command.create({
'field_name': 'company_id',
'domain': f"[('account_tax_unit_ids', 'in', {tax_unit.id})]",
}),
],
}
for tax_unit in res
])
generic_tax_report = self.env.ref('account.generic_tax_report')
generic_tax_report.horizontal_group_ids |= horizontal_groups
generic_tax_report_account_tax = self.env.ref('account.generic_tax_report_account_tax')
generic_tax_report_account_tax.horizontal_group_ids |= horizontal_groups
generic_tax_report_tax_account = self.env.ref('account.generic_tax_report_tax_account')
generic_tax_report_tax_account.horizontal_group_ids |= horizontal_groups
generic_ec_sales_report = self.env.ref('account_reports.generic_ec_sales_report')
generic_ec_sales_report.horizontal_group_ids |= horizontal_groups
for tax_unit in res:
generic_tax_report.variant_report_ids.filtered(lambda variant: variant.country_id == tax_unit.country_id).write(
{
'horizontal_group_ids': [Command.link(group.id) for group in horizontal_groups],
}
)
self.env['account.return.type']._generate_or_refresh_all_returns(res.company_ids.root_id)
return res
def write(self, vals):
root_companies_before = self.company_ids.root_id
result = super().write(vals)
if any(return_field in vals for return_field in ('main_company_id', 'company_ids', 'country_id')):
self.env['account.return.type']._generate_or_refresh_all_returns(root_companies_before | self.company_ids.root_id)
return result
@api.depends('company_ids')
def _compute_fiscal_position_completion(self):
for unit in self:
synced = True
for company in unit.company_ids:
origin_company = company._origin
fp = unit._get_tax_unit_fiscal_positions(companies=origin_company)
all_partners_with_fp = self.env['res.company'].search([]).with_company(origin_company).partner_id\
.filtered(lambda p: p.property_account_position_id == fp) if fp else self.env['res.partner']
synced = all_partners_with_fp == (unit.company_ids - origin_company).partner_id
if not synced:
break
unit.fpos_synced = synced
def _get_tax_unit_fiscal_positions(self, companies, create_or_refresh=False):
"""
Retrieves or creates fiscal positions for all companies specified.
These fiscal positions have no taxes, so this could probably be simplified (as refresh makes no sense anymore)
@param {recordset} companies: companies for which to find/create fiscal positions
@param {boolean} create_or_refresh: a boolean indicating whether the fiscal positions should be created if not found
@return {recordset} all the fiscal positions found/created for the companies requested.
"""
fiscal_positions = self.env['account.fiscal.position'].with_context(allowed_company_ids=self.env.user.company_ids.ids)
for unit in self:
for company in companies:
fp_identifier = 'account.tax_unit_%s_fp_%s' % (unit.id, company.id)
existing_fp = self.env.ref(fp_identifier, raise_if_not_found=False)
if create_or_refresh:
data = {
'xml_id': fp_identifier,
'values': {
'name': unit.name,
'company_id': company.id,
}
}
existing_fp = fiscal_positions._load_records([data])
if existing_fp:
fiscal_positions += existing_fp
return fiscal_positions
def action_sync_unit_fiscal_positions(self):
self._get_tax_unit_fiscal_positions(companies=self.env['res.company'].search([])).unlink()
for unit in self:
for company in unit.company_ids:
fp = unit._get_tax_unit_fiscal_positions(companies=company, create_or_refresh=True)
(unit.company_ids - company).with_company(company).partner_id.property_account_position_id = fp
def unlink(self):
# EXTENDS base
self._get_tax_unit_fiscal_positions(companies=self.env['res.company'].search([])).unlink()
return super().unlink()
@api.constrains('country_id', 'company_ids')
def _validate_companies_country(self):
for record in self:
currencies = set()
for company in record.company_ids:
currencies.add(company.currency_id)
if any(unit != record and unit.country_id == record.country_id for unit in company.account_tax_unit_ids):
raise ValidationError(_("Company %(company)s already belongs to a tax unit in %(country)s. A company can at most be part of one tax unit per country.", company=company.name, country=record.country_id.name))
if len(currencies) > 1:
raise ValidationError(_("A tax unit can only be created between companies sharing the same main currency."))
@api.constrains('company_ids', 'main_company_id')
def _validate_main_company(self):
for record in self:
if record.main_company_id not in record.company_ids:
raise ValidationError(_("The main company of a tax unit has to be part of it."))
@api.constrains('company_ids')
def _validate_companies(self):
for record in self:
if len(record.company_ids) < 2:
raise ValidationError(_("A tax unit must contain a minimum of two companies. You might want to delete the unit."))
@api.onchange('vat', 'country_id')
def _onchange_vat(self):
self.vat, _country_code = self.env['res.partner']._run_vat_checks(self.country_id, self.vat, validation=False)
def _inverse_vat(self):
for record in self:
if not record.vat:
continue
_vat, checked_country_code = self.env['res.partner']._run_vat_checks(record.country_id, record.vat,
partner_name=_("tax unit [%s]", record.name))
if checked_country_code and checked_country_code != record.country_id.code:
raise ValidationError(_("The country detected for this VAT number does not match the one set on this Tax Unit."))
@api.onchange('company_ids')
def _onchange_company_ids(self):
if self.main_company_id not in self.company_ids and self.company_ids:
self.main_company_id = self.company_ids[0]._origin
elif not self.company_ids:
self.main_company_id = False

View File

@@ -0,0 +1,593 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import json
import datetime
from collections import defaultdict
from odoo import api, models, _, fields
from odoo.tools import SQL, groupby, frozendict
from odoo.fields import Domain
class AccountTrialBalanceReportHandler(models.AbstractModel):
_name = 'account.trial.balance.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Trial Balance Custom Handler'
############################
# OPTIONS INITIALIZATION #
############################
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
if options.get('comparison'):
options['comparison']['period_order'] = 'ascending' # Make comparisons ascending (always)
options['comparison']['hide_period_order_filter'] = True
# Modify column headers and group structure
column_headers, columns = self._get_column_values(report, options)
options['column_headers'][0] = column_headers
options['columns'] = columns
# CTA
for group_vals in options['column_groups']:
if group_vals['forced_options']['trial_balance_column_type'] in ('initial_balance', 'end_balance'):
group_vals['forced_options']['no_impact_on_currency_table'] = True
options['custom_display_config'] = {
'pdf_export': {
'pdf_export_main': 'account_reports.audit_pdf_export_main',
'pdf_export_main_table_header': 'account_reports.audit_pdf_export_main_table_header',
'pdf_export_main_table_body': 'account_reports.audit_pdf_export_main_table_body',
},
}
def _get_column_values(self, report, options):
"""
Generate and process column values for the trial balance report.
Returns modified column headers, column groups, and columns.
"""
headers = []
columns = []
original_headers = options['column_headers'][0]
original_columns = options['columns']
initial_date_from = fields.Date.to_date(
options['column_groups'][original_columns[0]['column_group_index']]['forced_options']['date']['date_from']
)
previous_fiscal_year = self.env.company.compute_fiscalyear_dates(initial_date_from)
block_id = 0
# Add initial balance column
initial_date_to = initial_date_from - datetime.timedelta(days=1)
block_end_date = fields.Date.to_date(options['column_groups'][0]['forced_options']['date']['date_to'])
headers, columns = self._add_initial_column(
report, options, headers, columns, initial_date_to, block_id, previous_fiscal_year['date_from'], block_end_date=block_end_date,
)
last_column = {}
nb_columns_per_header = len(original_columns) / len(original_headers)
col_number_in_block = 0
fiscal_year = {}
for column in original_columns:
column_group_values = options['column_groups'][column['column_group_index']]
fiscal_year = self.env.company.compute_fiscalyear_dates(
fields.Date.to_date(column_group_values['forced_options']['date']['date_from'])
)
# Check for fiscal year change
if fiscal_year != previous_fiscal_year:
headers, columns = self._add_end_column(report, options, headers, columns, last_column, block_id, previous_fiscal_year)
block_id += 1
initial_date_to = fields.Date.to_date(column_group_values['forced_options']['date']['date_from']) - datetime.timedelta(days=1)
block_end_date = fields.Date.to_date(column_group_values['forced_options']['date']['date_to'])
headers, columns = self._add_initial_column(report, options, headers, columns, initial_date_to, block_id, fiscal_year['date_from'], block_end_date=block_end_date)
previous_fiscal_year = fiscal_year
# Update column group
if column['column_group_index'] != last_column.get('column_group_index'):
column_group_values['forced_options'].update({
'trial_balance_column_block_id': str(block_id),
'trial_balance_column_type': 'period',
'trial_balance_block_fiscalyear_start': fields.Date.to_string(fiscal_year['date_from']),
'trial_balance_block_end_date': fields.Date.to_string(block_end_date),
})
# Handle column headers
col_number_in_block += 1
if col_number_in_block % nb_columns_per_header == 0:
headers.append(original_headers.pop(0))
columns.append(column)
last_column = column
headers, columns = self._add_end_column(report, options, headers, columns, last_column, block_id, fiscal_year)
return headers, columns
def _add_initial_column(self, report, options, headers, columns, date_to, block_id, fiscal_year_start, block_end_date=None):
initial_dates = report._build_date_dict(options, None, date_to, mode='single')
header, col = self._create_column(report, options, _("Initial Balance"), initial_dates, block_id, fiscal_year_start, 'initial_balance', block_end_date)
headers.append(header)
columns.extend(col)
return headers, columns
def _add_end_column(self, report, options, headers, columns, last_column, block_id, fiscal_year):
last_group = options['column_groups'][last_column['column_group_index']]
end_date_from = fields.Date.to_date(last_group['forced_options']['date']['date_from'])
end_date_to = fields.Date.to_date(last_group['forced_options']['date']['date_to'])
end_dates = report._build_date_dict(options, end_date_from, end_date_to)
header, col = self._create_column(report, options, _("End Balance"), end_dates, block_id, fiscal_year['date_from'], 'end_balance', block_end_date=end_date_to)
headers.append(header)
columns.extend(col)
return headers, columns
def _create_column(self, report, options, header_name, period_dates, block_id, fiscal_year_start, column_type, block_end_date=None):
header, cols = self._generate_column_group(
report, options,
new_header_name=header_name,
new_values={
'forced_options': {
'date': period_dates,
'trial_balance_column_block_id': str(block_id),
'trial_balance_column_type': column_type,
'trial_balance_block_fiscalyear_start': fields.Date.to_string(fiscal_year_start),
'trial_balance_block_end_date': fields.Date.to_string(block_end_date) if block_end_date else options['date']['date_to'],
},
},
create_single_column=self._display_single_column_for_initial_and_end_sections(options),
)
return header, cols
@api.model
def _display_single_column_for_initial_and_end_sections(self, options):
# Decide whether we want our Initial Balance and End Balance column groups to have a single 'Balance' column.
# If there is more than one header level, the front-end can't handle different number of columns depending
# on the column header, so we need to use 'debit' and 'credit' columns rather than a 'balance' column.
create_single_column = len(options['column_headers']) == 1
return create_single_column
def _generate_column_group(self, report, options, new_header_name, new_values, create_single_column=True):
""" Generate column header, column group and columns values for a new column group.
This is used to insert Initial Balance and End Balance columns before / after
the period columns.
If `create_single_column` is True, we will create a single 'Balance' column instead
a column per report column.
"""
default_group_vals = {'horizontal_groupby_element': {}, 'forced_options': {}, **new_values}
new_column_header_element = {'name': new_header_name, 'forced_options': {}, **new_values}
if create_single_column:
new_column_header_element['colspan'] = 1
column_headers = [
[new_column_header_element],
*options['column_headers'][1:],
]
new_column_group_vals = report._generate_columns_group_vals_recursively(column_headers, default_group_vals)
new_columns = report._build_columns_from_column_group_vals(options, new_column_group_vals)
if create_single_column:
# _build_columns_from_column_group_vals creates a column group with all the columns defined in the report.
# But we'd like to have just one 'Balance' column, so we edit columns here.
column_name = _("Balance")
new_columns = [
{
**new_column,
'name': column_name,
'expression_label': 'balance',
}
for new_column in new_columns
if new_column['expression_label'] == 'debit'
]
return new_column_header_element, new_columns
def _caret_options_initializer(self):
return {
'account.account': [
{'name': _("General Ledger"), 'action': 'caret_option_open_general_ledger'},
{'name': _("Journal Items"), 'action': 'open_journal_items'},
],
'undistributed_profits_losses': [
{'name': _("General Ledger"), 'action': 'caret_option_open_general_ledger'},
{'name': _("Journal Items"), 'action': 'open_unallocated_items_journal_items'},
],
}
def open_unallocated_items_journal_items(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
return report.open_unallocated_items_journal_items(options, params)
###################
# REPORT ENGINE #
###################
def _report_engine_trial_balance(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
""" The custom engine for the Trial Balance.
Return a list of lines with keys {'balance', 'debit', 'credit'} that are the aggregation
of the journal items specified by the options' domain and dates.
"""
report = self.env['account.report'].browse(options['report_id'])
# This is because we want to pass a list of fields via the 'current_groupby' argument when calling this method
# from the _custom_unfold_all_batch_data_generator.
current_groupbys = [current_groupby] if current_groupby and not isinstance(current_groupby, list) else current_groupby or []
report._check_groupby_fields(current_groupbys)
# Never expand individual AMLs if we are in the Initial Balance.
if 'id' in current_groupbys and options['trial_balance_column_type'] == 'initial_balance':
return {next(iter(formulas_dict.values())): []}
extra_domain = []
# Don't consider income and expense AMLs from previous fiscal years.
# (1) This is an optimization that speeds up the report but prevents expanding the Unaffected Earnings account.
# (2) This also has the functional purpose of ensuring that income and expense accounts only take into account AMLs
# from the current fiscal year when coming from the `_expand_groupby`, because the `_expand_groupby` only adds
# a forced_domain on 'account_id' and doesn't do any restriction based on date.
if fiscalyear_start := options.get('trial_balance_block_fiscalyear_start'):
extra_domain = [
'|',
('account_id.include_initial_balance', '=', True),
('date', '>=', fiscalyear_start),
]
if options.get('export_mode') == 'print' and options.get('filter_search_bar'):
extra_domain.append(('account_id', 'ilike', options['filter_search_bar']))
block_end_date = None
if options['trial_balance_column_type'] == 'initial_balance':
date_scope = 'from_beginning'
block_end_date = options.get('trial_balance_block_end_date')
query = report._get_report_query(options, date_scope, domain=extra_domain, cta_date_to=block_end_date)
if current_groupbys:
select_groupby_key_components = SQL(',\n').join(
SQL("%s AS %s", self.env['account.move.line']._field_to_sql("account_move_line", groupby_key, query), SQL.identifier(f'groupby_key_{groupby_key}'))
for groupby_key in current_groupbys
)
query.groupby = SQL(',').join(SQL.identifier(f'groupby_key_{groupby_key}') for groupby_key in current_groupbys)
query_results = self.env.execute_query_dict(query.select(SQL(', ').join(s for s in (
SQL('%s', select_groupby_key_components) if current_groupbys else SQL(),
SQL('COALESCE(SUM(%s), 0.0) AS balance', query.table.consolidation_balance),
SQL('COALESCE(SUM(%s), 0.0) AS credit', query.table.consolidation_credit),
SQL('COALESCE(SUM(%s), 0.0) AS debit', query.table.consolidation_debit),
) if s)))
if not current_groupbys:
if not query_results:
return {next(iter(formulas_dict.values())): {
'balance': 0.0,
'debit': 0.0,
'credit': 0.0,
'has_sublines': False,
}}
query_result = query_results[0]
query_result['has_sublines'] = True
return {next(iter(formulas_dict.values())): query_result}
return {next(iter(formulas_dict.values())): [
(
(
query_result[f'groupby_key_{current_groupbys[0]}']
if len(current_groupbys) == 1
else tuple(query_result[f'groupby_key_{groupby}'] for groupby in current_groupbys)
),
{**query_result, 'has_sublines': True},
)
for query_result in query_results
]}
def _custom_groupby_line_completer(self, report, options, line_dict, current_groupby):
if line_dict.groupby != 'id':
return
# Don't expand individual AMLs in the Initial Balance
unfoldable = False
for column in line_dict.columns:
column_options = options['column_groups'][column.column_group_index]['forced_options']
if column_options['trial_balance_column_type'] == 'initial_balance':
column.has_sublines = False
unfoldable = unfoldable or column.has_sublines
line_dict.unfoldable = unfoldable
def _custom_line_postprocessor(self, report, options, lines):
""" Compute the end balance for each column block and each horizontal group,
based on the initial balance and the period debits and credits in the same
column block and horizontal group.
Any value that was already in the end_balance column is ignored.
"""
def get_block_and_group_key(column):
col_group_index = column.column_group_index
if col_group_index is None:
return None, frozendict(), ()
column_group = options['column_groups'][col_group_index]
block_id = column_group['forced_options'].get('trial_balance_column_block_id')
horizontal_group = frozendict(column_group.get('horizontal_groupby_element', {}))
analytic_group = tuple(column_group['forced_options'].get('analytic_accounts_list', []))
return block_id, horizontal_group, analytic_group
# Unaffected Earnings lines
if report._parse_line_id(lines[0].id)[-1] == ('', 'account.report.line', report.line_ids[0].id):
unaffected_earning_lines = report._get_unallocated_earnings_lines(options, 'strict_range', auditable=True)
else:
unaffected_earning_lines = []
if report.currency_translation == 'cta':
cta_line = report._compute_cumulative_translation_adjustment_lines(options, 'strict_range')
cumulative_translation_adjustment_lines = [cta_line] if cta_line else []
else:
cumulative_translation_adjustment_lines = []
if self.env.company.totals_below_sections:
total_line_id = lines[-1].id
else:
total_line_id = lines[0].id
unaffected_earning_values = defaultdict(
lambda: {
'initial_balance': {'debit': 0, 'credit': 0, 'balance': 0},
'period': {'debit': 0, 'credit': 0, 'balance': 0},
}
)
cumulative_translation_adjustment_values = defaultdict(
lambda: {
'initial_balance': {'debit': 0, 'credit': 0, 'balance': 0},
'period': {'debit': 0, 'credit': 0, 'balance': 0},
}
)
for line in unaffected_earning_lines + cumulative_translation_adjustment_lines + lines:
unaffected_earning_line = report._get_markup(line.id) == 'undistributed_profits_losses'
cumulative_translation_adjustment_line = report._get_markup(line.id) == 'cumulative_translation_adjustment'
# Group by column block ID and horizontal groupby element to sum up end balance
grouped_by_block = groupby(line.columns, key=get_block_and_group_key)
for _grouping_key, columns_in_block in grouped_by_block:
columns_grouped_by_type = dict(groupby(
columns_in_block,
lambda column: (
options['column_groups'][column.column_group_index]['forced_options'].get('trial_balance_column_type')
if column.column_group_index is not None else None
)
))
# We do a separate sum for debits and credits since we need to handle both the case where
# there is a single Balance column (if there is no horizontal groupby) or separate Debit and
# Credit columns in the initial balance and end balance (if there is a horizontal groupby)
sum_debit = sum_credit = 0.0
for col_type, cols in columns_grouped_by_type.items():
if col_type in ('initial_balance', 'period'):
for col in cols:
if line.id == total_line_id:
col.no_format += unaffected_earning_values[_grouping_key][col_type][col.expression_label]
col.no_format += cumulative_translation_adjustment_values[_grouping_key][col_type][col.expression_label]
col.is_zero = not bool(col.no_format)
if not col.is_zero:
if col.expression_label == 'debit' or (col.expression_label == 'balance' and col in columns_grouped_by_type['initial_balance']):
sum_debit += col.no_format
elif col.expression_label == 'credit':
sum_credit += col.no_format
if unaffected_earning_line:
unaffected_earning_values[_grouping_key][col_type][col.expression_label] += col.no_format
if cumulative_translation_adjustment_line:
cumulative_translation_adjustment_values[_grouping_key][col_type][col.expression_label] += col.no_format
for end_balance_col in columns_grouped_by_type.get('end_balance', []):
match end_balance_col.expression_label:
case 'debit':
end_balance_col.no_format = sum_debit
end_balance_col.is_zero = not bool(sum_debit)
case 'credit':
end_balance_col.no_format = sum_credit
end_balance_col.is_zero = not bool(sum_credit)
case 'balance':
balance = sum_debit - sum_credit
end_balance_col.no_format = balance
end_balance_col.is_zero = not bool(balance)
# Total line
if lines and not lines[0].parent_id: # should not affect when unfolding lines
# The same behavior is expected with or without totals_below_sections activated
# Only the total line should be displayed at the bottom, in bold
if self.env.company.totals_below_sections: # total line already exists
lines.pop(0)
if unaffected_earning_lines:
total_line = lines.pop(-1)
lines.extend(unaffected_earning_lines)
lines.append(total_line)
if cumulative_translation_adjustment_lines and not all(col.is_zero for col in cumulative_translation_adjustment_lines[0].columns):
total_line = lines.pop(-1)
lines.extend(cumulative_translation_adjustment_lines)
lines.append(total_line)
else:
lines.extend(unaffected_earning_lines)
if cumulative_translation_adjustment_lines and not all(col.is_zero for col in cumulative_translation_adjustment_lines[0].columns):
lines.extend(cumulative_translation_adjustment_lines)
lines.append(lines.pop(0))
# To make the style as if totals_below_sections was activated
lines[-1].id = report._build_subline_id(lines[-1].id, report._build_line_id([('total', None, None)]))
# To make totals line not blank
for col in lines[-1].columns:
col.blank_if_zero = False
lines[-1].name = self.env._("Total")
return lines
def _report_expand_unfoldable_line_with_groupby(self, line_dict_id, groupby, options, unfold_all_batch_data=None, limit_to_load=None):
""" Shallow the 'account.report' function to prevent displaying move lines that do not belong to the period that is selected """
if limit_to_load and groupby.replace(' ', '').split(',')[0] == 'account_id':
# Done for usability. We don't apply any load more limit for that grouping, assuming the number of accounts will always be small enough
limit_to_load = None
report = self.env['account.report'].browse(options['report_id'])
if groupby != 'id':
return report._report_expand_unfoldable_line_with_groupby(line_dict_id, groupby, options, unfold_all_batch_data=unfold_all_batch_data, limit_to_load=limit_to_load)
for _col_group_index, col_group_vals in enumerate(options['column_groups']):
if col_group_vals['forced_options']['trial_balance_column_type'] == 'initial_balance':
col_group_vals['forced_domain'].append(('id', '=', False))
return report._report_expand_unfoldable_line_with_groupby(line_dict_id, groupby, options, unfold_all_batch_data=unfold_all_batch_data, limit_to_load=limit_to_load)
def _get_account_ids_type_map(self, report, options):
company_ids = report.get_report_company_ids(options)
accounts = self.env['account.account'].search_fetch([('company_ids', 'in', company_ids)], ['account_type'])
account_dict = {account.id: account.account_type for account in accounts}
return account_dict
def _get_fiscalyear_start_date(self, options):
return options.get('trial_balance_block_fiscalyear_start')
def _custom_unfold_all_batch_data_generator(self, report, options, lines_to_expand_by_function):
""" Generate the custom engine's results for each full-sub-groupby-key that
would be created when doing an unfold-all on the report.
"""
def get_sub_groupby_key(report_line_id, groupbys, grouping_key):
previous_groupbys, current_groupby = groupbys[:-1], groupbys[-1]
sub_groupby_key = f'[{report_line_id}]'
sub_groupby_key += ','.join(
f'{field_name}:{value or None}'
for (field_name, value) in zip(previous_groupbys, grouping_key)
)
sub_groupby_key += f'=>{current_groupby}'
return sub_groupby_key
results = {} # In the form {full_sub_groupby_key: all_column_group_expression_totals for this groupby computation}
for line_to_expand in lines_to_expand_by_function.get('_report_expand_unfoldable_line_with_groupby', []):
report_line_id = report._get_res_id_from_line_id(line_to_expand.id, 'account.report.line')
report_line = self.env['account.report.line'].browse(report_line_id)
expressions = report_line.expression_ids.filtered(
lambda x: x.engine == 'custom' and x.formula == '_report_engine_trial_balance'
)
if len(expressions) != len(report_line.expression_ids):
continue
formulas_dict = {expressions[0].formula: expressions}
groupby_str = report_line._get_groupby(options)
groupbys = groupby_str.replace(' ', '').split(',')
# Execute the query once for each groupby level. While we could optimize this further
# (execute the query once at the deepest groupby level, and then aggregate the results in Python),
# this ensures that the results match exactly what we would get by expanding each line.
# But we could change that if there is a performance need.
while groupbys:
for column_group_index, column_group_options in report._split_options_per_column_group(options).items():
for date_scope, expressions_by_date_scope in groupby(expressions, lambda e: e.date_scope):
# Get the custom engine results for the given groupby level.
engine_res = self._report_engine_trial_balance(column_group_options, date_scope, formulas_dict, current_groupby=groupbys)
# Transform the groupby key of each line into a list
engine_lines = [
(grouping_key if isinstance(grouping_key, tuple) else (grouping_key,), line_values)
for formula_res in engine_res.values()
for grouping_key, line_values in formula_res
]
for parent_line_grouping_key, engine_lines_grouped_by_parent_line in groupby(
engine_lines,
lambda l: tuple(l[0][:-1])
):
full_sub_groupby_key = get_sub_groupby_key(report_line_id, groupbys, parent_line_grouping_key)
results.setdefault(full_sub_groupby_key, {})
results[full_sub_groupby_key][column_group_index] = {
expression: {
'value': [
(grouping_key[-1], line_values[expression.subformula])
for grouping_key, line_values in engine_lines_grouped_by_parent_line
],
'sublines_info': {
grouping_key[-1]
for grouping_key, line_values in engine_lines_grouped_by_parent_line
if line_values['has_sublines']
},
}
for expression in expressions_by_date_scope
}
groupbys.pop()
return results
def action_audit_cell(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
column_group_forced_options = options['column_groups'][params['column_group_index']]['forced_options']
# When generating the end balance column, we didn't specify a date in the forced_options,
# to avoid a separate call to the custom engine (instead, the end balance is computed in
# the custom lines postprocessor.)
# But when auditing an end balance line, we need to retrieve moves from the beginning of time,
# so we modify the options here just for the call to report.action_audit_cell.
if column_group_forced_options['trial_balance_column_type'] == 'end_balance':
column_group_forced_options['date'].update({
'mode': 'single',
'date_from': None,
})
action = report.action_audit_cell(options, params)
account_id = report._get_res_id_from_line_id(params['calling_line_dict_id'], 'account.account')
account = self.env['account.account'].browse(account_id)
modified_domain = []
if not account:
action['domain'] += report._get_unallocated_earnings_lines_domain(
column_group_forced_options['trial_balance_block_fiscalyear_start'],
report._get_res_id_from_line_id(params['calling_line_dict_id'], 'res.company')
)
elif (
column_group_forced_options['trial_balance_column_type'] in ('initial_balance', 'end_balance')
and (account.internal_group in ('income', 'expense') or account.account_type == 'equity_unaffected')
):
for condition in action['domain']:
match condition:
case ['account_id', '=', account_id]:
modified_domain.extend([
('account_id', '=', account_id),
('date', '>=', column_group_forced_options['trial_balance_block_fiscalyear_start']),
])
case _:
modified_domain.append(condition)
action['domain'] = modified_domain
date_from, date_to = report._get_date_bounds_info(options, 'strict_range')
if report._get_markup(params['calling_line_dict_id']) == 'undistributed_profits_losses':
date_from = column_group_forced_options['date']['date_from']
date_to = column_group_forced_options['date']['date_to']
action['context'].update({
'currency_translation': report.currency_translation,
'date_from': date_from,
'date_to': date_to,
})
if options.get('multi_currency'):
action['views'] = [(self.env.ref('account_reports.view_multi_currency_report_audit').id, 'list')]
if report._get_markup(params['calling_line_dict_id']) == 'cumulative_translation_adjustment':
column_group_options = report._get_column_group_options(options, params.get('column_group_index'))
action['views'] = [(self.env.ref('account_reports.view_cumulative_translation_adjustment_audit_tree').id, 'list')]
action['domain'] = Domain.AND([
report._get_options_domain(column_group_options, 'strict_range'),
Domain('account_type', 'in', ['equity', 'equity_unaffected', 'income', 'income_other', 'expense_direct_cost', 'expense', 'expense_depreciation', 'expense_other'])])
return action

View File

@@ -0,0 +1,56 @@
from odoo import models
from odoo.fields import Domain
class AccountBalanceSheetReportHandler(models.AbstractModel):
_name = 'account.balance.sheet.report.handler'
_inherit = ['account.report.custom.handler']
_description = "Balance Sheet Custom Handler"
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
companies = self.env['res.company'].browse(report.get_report_company_ids(options))
has_cta_expr = any(
expression.formula == '_report_engine_cumulative_translation_adjustment'
for line in report.line_ids
for expression in line.expression_ids
)
if report.currency_translation == 'cta' and len(companies.currency_id) > 1 and not has_cta_expr:
warnings['account_reports.common_possibly_unbalanced_because_cta'] = {}
def action_audit_cell(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
report_line = self.env['account.report.line'].browse(params['report_line_id'])
action = report.action_audit_cell(options, params)
date_from, date_to = report._get_date_bounds_info(options, 'strict_range')
action['context'].update({
'currency_translation': report.currency_translation,
'date_from': date_from,
'date_to': date_to,
})
if options.get('multi_currency'):
action['views'] = [(self.env.ref('account_reports.view_multi_currency_report_audit').id, 'list')]
if report_line.code in ('CTA', 'OCI'):
column_group_options = report._get_column_group_options(options, params.get('column_group_index'))
action['views'] = [(self.env.ref('account_reports.view_cumulative_translation_adjustment_audit_tree').id, 'list')]
action['domain'] = Domain.AND([
report._get_options_domain(column_group_options, 'strict_range'),
Domain('account_type', 'in', ['equity', 'equity_unaffected', 'income', 'income_other', 'expense_direct_cost', 'expense', 'expense_depreciation', 'expense_other']),
])
action['context'].update({
'group_by': ['account_type', 'account_id']
})
return action
def _report_engine_cumulative_translation_adjustment(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
report = self.env['account.report'].browse(options['report_id'])
cumulative_translation_adjustment = report._compute_cumulative_translation_adjustment(options, date_scope)
return {
expression: {k: -v for k, v in cumulative_translation_adjustment.items()} # opposite sign because OCI are in the liabilities
for formula, expressions in formulas_dict.items()
for expression in expressions
}

View File

@@ -0,0 +1,789 @@
import ast
from datetime import date
from dateutil.relativedelta import relativedelta
from odoo import fields, models
from odoo.fields import Domain
from odoo.tools import SQL
class AccountBankReconciliationReportHandler(models.AbstractModel):
_name = 'account.bank.reconciliation.report.handler'
_inherit = ['account.report.custom.handler']
_description = 'Bank Reconciliation Report Custom Handler'
######################
# Options
######################
def _custom_options_initializer(self, report, options, previous_options):
super()._custom_options_initializer(report, options, previous_options=previous_options)
# Options is needed otherwise some elements added in the post processor go on the total line
if 'active_id' in self.env.context and self.env.context.get('active_model') == 'account.journal':
options['bank_reconciliation_report_journal_id'] = self.env.context['active_id']
elif 'bank_reconciliation_report_journal_id' in previous_options:
options['bank_reconciliation_report_journal_id'] = previous_options['bank_reconciliation_report_journal_id']
else:
# This should never happen except in some test cases
options['bank_reconciliation_report_journal_id'] = self.env['account.journal'].search([('type', '=', 'bank')], limit=1).id
# Remove multi-currency columns if needed
is_multi_currency = self.env.user.has_group('base.group_multi_currency') and self.env.user.has_group('base.group_no_one')
if not is_multi_currency:
options['columns'] = [
column for column in options['columns']
if column['expression_label'] not in ('amount_currency', 'currency')
]
# This template override adds warning with tooltip on report lines.
options['custom_display_config'] = {
'templates': {
'AccountReportLineName': 'account_reports.BankReconciliationReportLineName',
},
}
# This removes journal groups option from the report like Local Gaap, IFRS.
# We don't need `journals` options as we get journal from `bank_reconciliation_report_journal_id`.
options.pop('journals', None)
######################
# Return function
######################
def _build_bank_reco_engine_result(self, date=None, label=None, amount_currency=None, amount_currency_currency_id=None, amount=0, amount_currency_id=None, has_sublines=False):
return {
'date': date,
'label': label,
'amount_currency': amount_currency,
'amount_currency_currency_id': amount_currency_currency_id,
'amount': amount,
'amount_currency_id': amount_currency_id,
'has_sublines': has_sublines,
}
######################
# Engine
######################
def _report_engine_forced_currency_amount(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
_journal, journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
return {next(iter(formulas_dict.values())): self._build_bank_reco_engine_result(amount_currency_id=journal_currency.id)}
def _report_engine_starting_balance(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
journal, journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
bank_balance, _st_line_ids = self._get_bank_balance_and_last_statement_lines(options, journal, 'to_beginning_of_period')
return {next(iter(formulas_dict.values())): self._build_bank_reco_engine_result(amount=bank_balance, amount_currency_id=journal_currency.id)}
def _report_engine_reconciled_receipts(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_common(options, 'receipts', current_groupby, formulas_dict, False)
def _report_engine_reconciled_payments(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_common(options, 'payments', current_groupby, formulas_dict, False)
def _report_engine_unreconciled_receipts(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_common(options, 'receipts', current_groupby, formulas_dict, True)
def _report_engine_unreconciled_payments(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_common(options, 'payments', current_groupby, formulas_dict, True)
def _report_engine_outstanding_receipts(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_outstanding_common(options, 'receipts', current_groupby, formulas_dict)
def _report_engine_outstanding_payments(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
return self._bank_reconciliation_report_custom_engine_outstanding_common(options, 'payments', current_groupby, formulas_dict)
def _report_engine_misc_operations(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
def build_result_dict(query_res_lines):
if current_groupby == 'id':
res = query_res_lines[0]
currency = self.env['res.currency'].browse(res['currency_id'])
convert = currency != journal_currency
return self._build_bank_reco_engine_result(
date=res['date'],
label=res['ref'],
amount_currency=res['amount_currency'] if convert else None,
amount_currency_currency_id=currency.id if convert else None,
amount=company_currency._convert(res['balance'], journal_currency, journal.company_id, options['date']['date_to']) if convert else res['amount_currency'],
amount_currency_id=journal_currency.id,
)
else:
amount = 0
for res in query_res_lines:
convert = self.env['res.currency'].browse(res['currency_id']) != journal_currency
amount += company_currency._convert(res['balance'], journal_currency, journal.company_id, options['date']['date_to']) if convert else res['amount_currency']
return self._build_bank_reco_engine_result(
amount=amount,
amount_currency_id=journal_currency.id,
has_sublines=bool(query_res_lines),
)
journal, journal_currency, company_currency = self._get_bank_journal_and_currencies(options)
exchange_journal = journal.company_id.currency_exchange_journal_id
bank_miscellaneous_domain = self._get_bank_miscellaneous_move_lines_domain(options, journal)
bank_miscellaneous_domain = Domain.AND([
bank_miscellaneous_domain,
[('journal_id', '!=', exchange_journal.id)]
])
base_query = report._get_report_query(options, 'strict_range', domain=bank_miscellaneous_domain or [])
groupby_field_sql = self.env['account.move.line']._field_to_sql('account_move_line', current_groupby, base_query) if current_groupby else SQL('NULL')
query_sql = SQL(
"""
SELECT
%(select_from_groupby)s,
account_move_line.ref,
account_move_line.date,
account_move_line.balance,
account_move_line.amount_currency,
account_move_line.currency_id
FROM %(table_references)s
WHERE %(search_condition)s
GROUP BY %(groupby)s,
account_move_line.ref,
account_move_line.date,
account_move_line.balance,
account_move_line.amount_currency,
account_move_line.currency_id
""",
select_from_groupby=SQL('%s AS grouping_key', groupby_field_sql),
table_references=base_query.from_clause,
search_condition=base_query.where_clause,
groupby=groupby_field_sql if current_groupby else SQL('account_move_line.ref'),
)
self.env.cr.execute(query_sql)
query_res_lines = self.env.cr.dictfetchall()
return {next(iter(formulas_dict.values())): self._compute_result(query_res_lines, current_groupby, build_result_dict)}
def _report_engine_gl_balance(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
report = self.env['account.report'].browse(options['report_id'])
journal, journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
gl_balance = self._get_gl_balance(options, report, journal, 'from_beginning')
return {next(iter(formulas_dict.values())): self._build_bank_reco_engine_result(amount=gl_balance, amount_currency_id=journal_currency.id)}
def _bank_reconciliation_report_custom_engine_common(self, options, internal_type, current_groupby, formulas_dict, unreconciled):
"""
Retrieve entries for bank reconciliation based on specified parameters.
Parameters:
- options (dict): A dictionary containing options of the report.
- internal_type (str): The internal type used for classification (e.g., receipt, payment, all). For the receipt
we will query the entries with a positive amounts and for the payment
the negative amounts.
If the internal type is all it will get all the
entries positive or negative.
- current_groupby (str): The current grouping criteria.
- formulas_dict (dict): A dictionary with custom engine method name as key and recordset of all expressions as value.
- unreconciled (bool): If True, query the unreconciled entries only. If False, query the reconciled entries only.
"""
journal, journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
if not journal:
return {next(iter(formulas_dict.values())): self._build_bank_reco_engine_result()}
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
def build_result_dict(query_res_lines):
# The query should find exactly one account move line per bank statement line
if current_groupby == 'id':
res = query_res_lines[0]
foreign_currency = self.env['res.currency'].browse(res['foreign_currency_id'])
rate = 1 # journal_currency / foreign_currency
if foreign_currency:
rate = (res['amount'] / res['amount_currency']) if res['amount_currency'] else 0
if unreconciled:
amount = -res['amount_residual'] * rate if res['amount_residual'] else None
amount_currency = -res['amount_residual'] if res['foreign_currency_id'] else None
elif res['is_reconciled']:
amount = res['amount'] if res['amount'] else None
amount_currency = res['amount_currency'] if res['foreign_currency_id'] else None
else:
amount = res['amount'] + res['amount_residual'] * rate if res['amount'] else None
amount_currency = res['amount_currency'] + res['amount_residual'] if res['foreign_currency_id'] else None
return self._build_bank_reco_engine_result(
date=res['date'] if res['date'] else None,
label=res['payment_ref'] or res['ref'] or '/',
amount_currency=amount_currency,
amount_currency_currency_id=foreign_currency.id if res['foreign_currency_id'] else None,
amount=amount,
amount_currency_id=journal_currency.id,
has_sublines=True,
)
else:
amount = 0
for res in query_res_lines:
rate = 1 # journal_currency / foreign_currency
if res['foreign_currency_id']:
rate = (res['amount'] / res['amount_currency']) if res['amount_currency'] else 0
if unreconciled:
amount += -res['amount_residual'] * rate
elif res['is_reconciled']:
amount += res['amount']
else:
amount += res['amount'] + res['amount_residual'] * rate
return self._build_bank_reco_engine_result(
amount=amount,
amount_currency_id=journal_currency.id,
has_sublines=bool(len(query_res_lines)),
)
query = report._get_report_query(options, 'strict_range', domain=[
('journal_id', '=', journal.id),
('account_id', '=', journal.default_account_id.id), # There should be only 1 line per move with that account
])
if internal_type == 'receipts':
st_line_amount_condition = SQL("AND st_line.amount > 0")
elif internal_type == 'payments':
st_line_amount_condition = SQL("AND st_line.amount < 0")
else:
st_line_amount_condition = SQL("")
if unreconciled:
# Fully unreconciled and partially reconciled transactions.
reconciliation_condition = SQL("AND st_line.is_reconciled IS NOT TRUE")
else:
# Fully reconciled and partially reconciled transactions.
reconciliation_condition = SQL("""
AND (
st_line.is_reconciled IS TRUE
OR (st_line.foreign_currency_id IS NULL AND -st_line.amount_residual != st_line.amount)
OR (st_line.foreign_currency_id IS NOT NULL AND -st_line.amount_residual != st_line.amount_currency)
)
""")
groupby_field_sql = self.env['account.move.line']._field_to_sql("account_move_line", current_groupby, query) if current_groupby else SQL('NULL')
# Build query
query = SQL(
"""
SELECT %(select_from_groupby)s,
st_line.id,
move.name,
move.ref,
move.date,
st_line.payment_ref,
st_line.amount,
st_line.amount_residual,
st_line.amount_currency,
st_line.foreign_currency_id,
st_line.is_reconciled
FROM %(table_references)s
JOIN account_bank_statement_line st_line ON st_line.move_id = account_move_line.move_id
JOIN account_move move ON move.id = st_line.move_id
WHERE %(search_condition)s
%(reconciliation_condition)s
%(st_line_amount_condition)s
GROUP BY %(group_by)s,
st_line.id,
move.id
""",
select_from_groupby=SQL("%s AS grouping_key", groupby_field_sql),
table_references=query.from_clause,
search_condition=query.where_clause,
reconciliation_condition=reconciliation_condition,
st_line_amount_condition=st_line_amount_condition,
group_by=groupby_field_sql if current_groupby else SQL('st_line.id'), # Same key in the groupby because we can't put a null key in a group by
)
self.env.cr.execute(query)
query_res_lines = self.env.cr.dictfetchall()
return {next(iter(formulas_dict.values())): self._compute_result(query_res_lines, current_groupby, build_result_dict)}
def _bank_reconciliation_report_custom_engine_outstanding_common(self, options, internal_type, current_groupby, formulas_dict):
"""
This engine retrieves the data of all recorded payments/receipts that have not been matched with a bank
statement yet
"""
journal, journal_currency, company_currency = self._get_bank_journal_and_currencies(options)
if not journal:
return {next(iter(formulas_dict.values())): self._build_bank_reco_engine_result()}
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
def build_result_dict(query_res_lines):
if current_groupby == 'id':
res = query_res_lines[0]
convert = not (journal_currency and res['currency_id'] == journal_currency.id)
amount_currency = res['amount_residual_currency']
balance = res['amount_residual']
foreign_currency = self.env['res.currency'].browse(res['currency_id'])
return self._build_bank_reco_engine_result(
date=res['date'] if res['date'] else None,
label=res['ref'] if res['ref'] else None,
amount_currency=amount_currency if convert else None,
amount_currency_currency_id=foreign_currency.id if convert else None,
amount=company_currency._convert(balance, journal_currency, journal.company_id, options['date']['date_to']) if convert else amount_currency,
amount_currency_id=journal_currency.id,
)
else:
amount = 0
for res in query_res_lines:
convert = not (journal_currency and res['currency_id'] == journal_currency.id)
if convert:
balance = res['amount_residual']
amount += company_currency._convert(balance, journal_currency, journal.company_id, options['date']['date_to'])
else:
amount += res['amount_residual_currency']
return self._build_bank_reco_engine_result(
amount=amount,
amount_currency_id=journal_currency.id,
has_sublines=bool(len(query_res_lines)),
)
accounts = journal._get_journal_inbound_outstanding_payment_accounts() + journal._get_journal_outbound_outstanding_payment_accounts()
query = report._get_report_query(options, 'from_beginning', domain=[
('journal_id', '=', journal.id),
('account_id', 'in', accounts.ids),
('full_reconcile_id', '=', False),
('amount_residual_currency', '!=', 0.0)
])
# Build query
groupby_field_sql = self.env['account.move.line']._field_to_sql("account_move_line", current_groupby, query) if current_groupby else SQL('NULL')
query = SQL(
"""
SELECT %(select_from_groupby)s,
account_move_line.account_id,
account_move_line.payment_id,
account_move_line.move_id,
account_move_line.currency_id,
account_move_line.move_name AS name,
account_move_line.ref,
account_move_line.date,
SUM(account_move_line.amount_residual) AS amount_residual,
SUM(account_move_line.balance) AS balance,
SUM(account_move_line.amount_residual_currency) AS amount_residual_currency,
SUM(account_move_line.amount_currency) AS amount_currency
FROM %(table_references)s
JOIN account_account account ON account.id = account_move_line.account_id
WHERE %(search_condition)s
AND %(is_receipt)s
GROUP BY %(group_by)s,
account_move_line.account_id,
account_move_line.payment_id,
account_move_line.move_id,
account_move_line.currency_id,
account_move_line.move_name,
account_move_line.ref,
account_move_line.date
""",
select_from_groupby=SQL("%s AS grouping_key", groupby_field_sql),
table_references=query.from_clause,
search_condition=query.where_clause,
is_receipt=SQL("account_move_line.balance > 0") if internal_type == "receipts" else SQL("account_move_line.balance < 0"),
group_by=groupby_field_sql if current_groupby else SQL('account_move_line.account_id'), # Same key in the groupby because we can't put a null key in a group by
)
self.env.cr.execute(query)
query_res_lines = self.env.cr.dictfetchall()
return {next(iter(formulas_dict.values())): self._compute_result(query_res_lines, current_groupby, build_result_dict)}
def _compute_result(self, query_res_lines, current_groupby, build_result_dict):
if not current_groupby:
return build_result_dict(query_res_lines)
else:
rslt = []
all_res_per_grouping_key = {}
for query_res in query_res_lines:
grouping_key = query_res['grouping_key']
all_res_per_grouping_key.setdefault(grouping_key, []).append(query_res)
for grouping_key, query_res_lines in all_res_per_grouping_key.items():
rslt.append((grouping_key, build_result_dict(query_res_lines)))
return rslt
def _custom_line_postprocessor(self, report, options, lines):
lines = super()._custom_line_postprocessor(report, options, lines)
journal, journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
if not journal:
return lines
date_from = fields.Date.from_string(options['date']['date_from']).strftime('%B %d %Y')
date_to = fields.Date.from_string(options['date']['date_to']).strftime('%B %d %Y')
amount_col_index = None
monetary_col_indexes = []
for index, col in enumerate(options['columns']):
if col['figure_type'] == 'monetary':
monetary_col_indexes.append(index)
if col['expression_label'] == 'amount':
amount_col_index = index
for line in lines:
if line.code == 'bank_name':
line.name = journal.default_account_id.display_name
elif line.code == 'starting_balance':
line.name = self.env._("Opening Bank Balance as of %(date_from)s", date_from=date_from)
line.css_class = 'o_bold_tr'
line.columns[amount_col_index].is_zero = False # We want this line to be always visible even with filter 'Hide lines at 0'.
amount_column = line.columns[amount_col_index]
if starting_balance_warning := self._get_gl_mismatch_warning(options, journal, journal_currency, report, amount_column.no_format, amount_column.format_params, 'to_beginning_of_period'):
line.update_values(**starting_balance_warning)
elif line.code == 'ending_balance':
line.name = self.env._("Calculated Ending Bank Balance as of %(date_to)s", date_to=date_to)
line.css_class = 'o_bold_tr'
line.columns[amount_col_index].is_zero = False
amount_column = line.columns[amount_col_index]
if ending_balance_warning := self._get_gl_mismatch_warning(options, journal, journal_currency, report, amount_column.no_format, amount_column.format_params, 'from_beginning'):
line.update_values(**ending_balance_warning)
elif line.code == 'gl_balance':
line.name = self.env._("Ending General Ledger Balance as of %(date_to)s", date_to=date_to)
line.css_class = 'line_level_0 text-info'
line.columns[amount_col_index].is_zero = False
elif line.code == 'misc_operations' and line.groupby and line.unfoldable and (misc_warning := self._get_misc_operations_warning(options, journal)):
line.update_values(**misc_warning)
line.columns[amount_col_index].is_zero = False
# Check if it's a leaf node
model, _model_id = report._get_model_info_from_id(line.id)
if model == "account.move.line":
line_name = line.name.split()
line.name = line_name[0] # This will give just the name without the ref or label
for col_index in monetary_col_indexes:
line.columns[col_index].css_class = ' ' # This prevents adding text-danger class for negative amounts.
return lines
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
journal, _journal_currency, _company_currency = self._get_bank_journal_and_currencies(options)
inconsistent_statements_line_ids = self._get_inconsistent_statements(options, journal).line_ids.ids
lines_without_statement_ids = self._get_st_lines_without_statement(options, journal).ids
if warnings is not None:
if inconsistent_statements_line_ids:
warnings['account_reports.inconsistent_statement_warning'] = {
'alert_type': 'warning',
'st_line_ids': inconsistent_statements_line_ids,
'name': self.env._("Inconsistent Statements"),
}
if lines_without_statement_ids:
warnings['account_reports.lines_without_statement_warning'] = {
'alert_type': 'info',
'st_line_ids': lines_without_statement_ids,
'name': self.env._("Transactions without Statement"),
}
######################
# Getter
######################
def _get_bank_journal_and_currencies(self, options):
"""
Retrieve the bank journal and its associated currencies.
:param options: The report options.
:return: A tuple of (bank journal, journal currency, company currency).
"""
journal = self.env['account.journal'].browse(options.get('bank_reconciliation_report_journal_id'))
company_currency = journal.company_id.currency_id
journal_currency = journal.currency_id or company_currency
return journal, journal_currency, company_currency
def _get_previous_period_date_options(self, options):
"""
Get the date option for the previous period.
:param options: The report options.
:return: A dictionary containing the date options for the previous period.
"""
date_option = self.env['account.report']._get_shifted_dates_period(options, options['date'], -1)
if options['date']['period_type'] == 'custom':
date_to = fields.Date.from_string(options['date']['date_from']) - relativedelta(days=1)
date_option = self.env['account.report']._build_date_dict(options, date_option['date_from'], date_to, 'custom')
return date_option
def _get_bank_balance_and_last_statement_lines(self, options, journal, date_scope='from_beginning'):
"""
Compute the bank balance and retrieve last statement lines.
:param options: The report options.
:param journal: The account.journal from which this report has been opened.
:param date_scope: The date scope to apply ('from_beginning' or 'to_beginning_of_period').
:return: A tuple of (bank balance, list of account.bank.statement.line ids).
"""
date_options = self._get_previous_period_date_options(options) if date_scope == 'to_beginning_of_period' else options['date']
report_date = fields.Date.from_string(date_options['date_to'])
move_state_condition = SQL("move.state != 'cancel'") if options['all_entries'] else SQL("move.state = 'posted'")
query = SQL(
"""
WITH statement_lines AS (
SELECT stl.id,
stl.amount,
stl.statement_id,
move.date
FROM account_bank_statement_line stl
JOIN account_move move
ON move.id = stl.move_id
WHERE stl.journal_id = %(journal_id)s
AND move.date <= %(report_date)s
AND %(move_state_condition)s
)
SELECT statement.id AS last_statement_id,
COALESCE(statement.balance_start, 0.0) AS balance_start,
COALESCE(stl_before_date.amount, 0.0) AS before_date_amount,
COALESCE(stl_before_date.ids, ARRAY[]::INTEGER[]) AS before_date_stl_ids,
COALESCE(unlinked_stl.amount, 0.0) AS unlinked_amount,
COALESCE(unlinked_stl.ids, ARRAY[]::INTEGER[]) AS unlinked_stl_ids
FROM (SELECT 1) seed
LEFT JOIN (
SELECT statement_id
FROM statement_lines
WHERE statement_id IS NOT NULL
ORDER BY date DESC, id DESC
LIMIT 1
) last_stl ON TRUE
LEFT JOIN account_bank_statement statement
ON statement.id = last_stl.statement_id
LEFT JOIN LATERAL (
SELECT SUM(amount) AS amount,
ARRAY_AGG(id) AS ids
FROM statement_lines
WHERE statement_id = statement.id
) stl_before_date ON TRUE
LEFT JOIN (
SELECT SUM(amount) AS amount,
ARRAY_AGG(id) AS ids
FROM statement_lines
WHERE statement_id IS NULL
) unlinked_stl ON TRUE
""",
journal_id=journal.id,
report_date=report_date,
move_state_condition=move_state_condition,
)
self.env.cr.execute(query)
res = self.env.cr.dictfetchall()[0]
if date_scope == 'to_beginning_of_period' and not (res['last_statement_id'] or res['unlinked_stl_ids']):
# Searching for first statement line instead of directly searching first statement
# because we might receive first statement after the selected period's end date
# but that statement's first transaction's date may be within the selected period.
first_statement = self.env['account.bank.statement.line'].search(
[
*self._get_st_lines_domain(options, journal),
('statement_id', '!=', False),
],
order='date, id', limit=1,
).statement_id
return first_statement.balance_start, first_statement.line_ids.ids
bank_balance = res['balance_start'] + res['before_date_amount'] + res['unlinked_amount']
st_line_ids = res['before_date_stl_ids'] + res['unlinked_stl_ids']
return bank_balance, st_line_ids
def _get_gl_balance(self, options, report, journal, date_scope):
"""
Retrieve the General Ledger balance for the given journal's bank account.
:param options: The report options.
:param report: The account.report record.
:param journal: The account.journal from which this report has been opened.
:param date_scope: The date scope to apply ('from_beginning' or 'to_beginning_of_period').
:return: The GL balance.
"""
domain = report._get_options_domain(options, date_scope)
gl_balance = journal._get_journal_bank_account_balance(domain=domain)[0]
return gl_balance
def _get_inconsistent_statements(self, options, journal):
"""
Retrieve the account.bank.statements records on the range of the options date having different starting
balance regarding its previous statement.
:param options: The report options.
:param journal: The account.journal from which this report has been opened.
:return: An account.bank.statements recordset.
"""
return self.env['account.bank.statement'].search([
('journal_id', '=', journal.id),
('date', '<=', options['date']['date_to']),
('is_valid', '=', False),
])
def _get_st_lines_without_statement(self, options, journal):
"""
Retrieve the account.bank.statement.line records on the range of the options date
which are not related to any bank statement.
:param options: The report options.
:param journal: The account.journal from which this report has been opened.
:return: An account.bank.statement.line recordset.
"""
return self.env['account.bank.statement.line'].search([
*self._get_st_lines_domain(options, journal),
('statement_id', '=', False),
])
def _get_st_lines_domain(self, options, journal):
"""
Get the domain to be used to retrieve statement lines upto selected period's end date.
:param options: The report options.
:param journal: The account.journal from which this report has been opened.
:return: A domain to search on the account.bank.statement.line model.
"""
return [
('journal_id', '=', journal.id),
('date', '<=', options['date']['date_to']),
('move_id.state', '!=', 'cancel') if options['all_entries'] else ('move_id.state', '=', 'posted'),
]
def _get_bank_miscellaneous_move_lines_domain(self, options, journal):
"""
Get the domain to be used to retrieve the journal items affecting the bank accounts but not linked to
a statement line. (Limited in a year)
:param options: The report options.
:param journal: The account.journal from which this report has been opened.
:return: A domain to search on the account.move.line model.
"""
if not journal.default_account_id:
return None
report = self.env['account.report'].browse(options['report_id'])
domain = [
('account_id', '=', journal.default_account_id.id),
('statement_line_id', '=', False),
*report._get_options_domain(options, 'from_beginning'),
]
fiscal_lock_date = journal.company_id._get_user_fiscal_lock_date(journal)
if fiscal_lock_date != date.min:
domain.append(('date', '>', fiscal_lock_date))
if journal.company_id.account_opening_move_id:
domain.append(('move_id', '!=', journal.company_id.account_opening_move_id.id))
return domain
def _get_gl_mismatch_warning(self, options, journal, journal_currency, report, bank_balance, format_params, date_scope):
gl_balance = self._get_gl_balance(options, report, journal, date_scope)
difference = bank_balance - gl_balance
if not journal_currency.is_zero(difference):
bank_balance = report._format_value(options, bank_balance, format_params=format_params, figure_type='monetary')
gl_balance = report._format_value(options, gl_balance, format_params=format_params, figure_type='monetary')
difference = report._format_value(options, difference, format_params=format_params, figure_type='monetary')
if date_scope == 'to_beginning_of_period':
warning_text = self.env._(
"The opening bank balance %(bank_balance)s does not match the General Ledger opening balance %(gl_balance)s for the selected report period, resulting in an unexplained difference of %(difference)s",
bank_balance=bank_balance,
gl_balance=gl_balance,
difference=difference,
)
else:
warning_text = self.env._(
"The calculated ending bank balance %(bank_balance)s does not match the General Ledger ending balance %(gl_balance)s for the selected report period, resulting in an unexplained difference of %(difference)s",
bank_balance=bank_balance,
gl_balance=gl_balance,
difference=difference,
)
return {
'warning_text': warning_text,
'warning_action': 'action_redirect_to_general_ledger',
'warning_params': {'date_scope': date_scope},
}
def _get_misc_operations_warning(self, options, journal):
bank_miscellaneous_domain = self._get_bank_miscellaneous_move_lines_domain(options, journal)
has_bank_miscellaneous_move_lines = bank_miscellaneous_domain and bool(self.env['account.move.line'].search_count(bank_miscellaneous_domain, limit=1))
if has_bank_miscellaneous_move_lines:
return {
'warning_text': self.env._(
"'%(account_name)s' account balance is affected by journal items which don't originate from a bank statement or payment.",
account_name=journal.default_account_id.display_name,
),
'warning_action': 'open_bank_miscellaneous_move_lines',
}
else:
return None
################
# Audit
################
def action_audit_cell(self, options, params):
report_line = self.env['account.report.line'].browse(params['report_line_id'])
if report_line.code == 'starting_balance':
journal = self.env['account.journal'].browse(options['bank_reconciliation_report_journal_id'])
_bank_balance, st_line_ids = self._get_bank_balance_and_last_statement_lines(options, journal, 'to_beginning_of_period')
return self.action_redirect_to_bank_statement_widget(options, {'st_line_ids': st_line_ids})
elif report_line.code == 'gl_balance':
return self.action_redirect_to_general_ledger(options, {'date_scope': 'from_beginning'})
return report_line.report_id.action_audit_cell(options, params)
################
# ACTIONS
################
def action_redirect_to_general_ledger(self, options, params):
"""
Action to redirect to the general ledger
:param options: The report options.
:param params: The action params containing 'date_scope'('from_beginning' or 'to_beginning_of_period').
:return: Actions to the report
"""
general_ledger_action = self.env['ir.actions.actions']._for_xml_id('account_reports.action_account_report_general_ledger')
if params.get('date_scope') == 'to_beginning_of_period':
general_ledger_options = {
**options,
'date': self._get_previous_period_date_options(options),
}
else:
general_ledger_options = options
general_ledger_action['params'] = {
'options': general_ledger_options,
'ignore_session': True,
}
context = ast.literal_eval(general_ledger_action['context'])
journal = self.env['account.journal'].browse(options.get('bank_reconciliation_report_journal_id'))
context['default_filter_accounts'] = journal.default_account_id.code
general_ledger_action['context'] = context
return general_ledger_action
def action_redirect_to_bank_statement_widget(self, options, params):
"""
Redirect the user to the requested bank statement, if empty displays all bank transactions of the journal.
:param options: The report options.
:param params: The action params containing at least 'st_line_ids' and 'name'.
:return: A dictionary representing an ir.actions.act_window.
"""
return self.env['account.bank.statement.line']._action_open_bank_reconciliation_widget(
default_context={'create': False},
extra_domain=[('id', 'in', params.get('st_line_ids'))],
name=params.get('name'),
)
def open_bank_miscellaneous_move_lines(self, options):
"""
An action opening the account.move.line list view affecting the bank account balance but not linked to
a bank statement line.
:param options: The report options.
:return: An action redirecting to the list view of journal items.
"""
journal = self.env['account.journal'].browse(options['bank_reconciliation_report_journal_id'])
return {
'name': self.env._('Journal Items'),
'type': 'ir.actions.act_window',
'res_model': 'account.move.line',
'views': [(self.env.ref('account.view_move_line_tree').id, 'list')],
'domain': self._get_bank_miscellaneous_move_lines_domain(options, journal),
}

View File

@@ -0,0 +1,118 @@
from itertools import zip_longest
from dateutil.relativedelta import relativedelta
from odoo import api, Command, fields, models, _
from odoo.exceptions import ValidationError
from odoo.tools import date_utils, float_is_zero, float_round
class AccountReportBudget(models.Model):
_name = 'account.report.budget'
_description = "Accounting Report Budget"
_order = 'sequence, id'
sequence = fields.Integer(string="Sequence")
name = fields.Char(string="Name", required=True)
item_ids = fields.One2many(string="Items", comodel_name='account.report.budget.item', inverse_name='budget_id')
company_id = fields.Many2one(string="Company", comodel_name='res.company', required=True, default=lambda x: x.env.company)
@api.constrains('name')
def _contrains_name(self):
for budget in self:
if not budget.name:
raise ValidationError(_("Please enter a valid budget name."))
@api.model_create_multi
def create(self, vals_list):
for values in vals_list:
if name := values.get('name'):
values['name'] = name.strip()
return super().create(vals_list)
def _create_or_update_budget_items(self, value_to_set, account_id, rounding, date_from, date_to):
""" This method will create / update several budget items following the number
of months between date_from(include) and date_to(include).
:param value_to_set: The value written by the user in the report cell.
:param account_id: The related account id.
:param rounding: The rounding for the decimal precision.
:param date_from: The start date for the budget item creation.
:param date_to: The end date for the budget item creation.
"""
self.ensure_one()
date_from, date_to = fields.Date.to_date(date_from), fields.Date.to_date(date_to)
if date_from != date_utils.start_of(date_from, 'month'):
date_from = (date_from.replace(day=1) + relativedelta(months=1))
existing_budget_items = self.env['account.report.budget.item'].search_fetch([
('budget_id', '=', self.id),
('account_id', '=', account_id),
('date', '<=', date_to),
('date', '>=', date_from),
], ['id', 'amount'])
existing_budget_items_by_date = {item.date: item for item in existing_budget_items}
total_amount = sum(existing_budget_items.mapped('amount'))
value_to_compute = value_to_set - total_amount
if float_is_zero(value_to_compute, precision_digits=rounding):
# In case the computed amount equals 0, we do an early return as
# it's not necessary to create new budget item
return
start_month_dates = [
date_utils.start_of(date, 'month')
for date in date_utils.date_range(date_from, date_to)
]
# Fill a list with the same amounts for each month
amounts = [float_round(value_to_compute / len(start_month_dates), precision_digits=rounding, rounding_method='DOWN')] * len(start_month_dates)
# Add the remainder in the last amount
amounts[-1] += float_round(value_to_compute - sum(amounts), precision_digits=rounding)
budget_items_commands = []
for start_month_date, amount in zip_longest(start_month_dates, amounts):
existing_budget_item = existing_budget_items_by_date.get(start_month_date)
if existing_budget_item:
budget_items_commands.append(Command.update(existing_budget_item.id, {
'amount': existing_budget_item.amount + amount,
}))
else:
budget_items_commands.append(Command.create({
'account_id': account_id,
'amount': amount,
'date': start_month_date,
}))
if budget_items_commands:
self.item_ids = budget_items_commands
# Make sure that the model is flushed before continuing the code and fetching these new items
self.env['account.report.budget.item'].flush_model()
def copy(self, default=None):
new_budgets = super().copy(default)
for old_budget, new_budget in zip(self, new_budgets):
for item in old_budget.item_ids:
item.copy({
'budget_id': new_budget.id,
'account_id': item.account_id.id,
'amount': item.amount,
'date': item.date,
})
return new_budgets
class AccountReportBudgetItem(models.Model):
_name = 'account.report.budget.item'
_description = "Accounting Report Budget Item"
budget_id = fields.Many2one(string="Budget", comodel_name='account.report.budget', required=True, index=True, ondelete='cascade')
account_id = fields.Many2one(
string="Account",
comodel_name='account.account',
domain="[('account_type', 'in', ('income', 'income_other', 'expense', 'expense_other', 'expense_depreciation', 'expense_direct_cost'))]",
required=True,
index=True,
)
amount = fields.Float(string="Amount", default=0)
date = fields.Date(required=True)

View File

@@ -0,0 +1,23 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import fields, models
from odoo.exceptions import UserError
class ExecutiveSummaryCustomHandler(models.AbstractModel):
_name = 'account.executive.summary.report.handler'
_inherit = 'account.report.custom.handler'
_description = 'Executive Summary Custom Handler'
def _report_engine_executive_summary_ndays(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
if current_groupby:
raise UserError(self.env._("NDays expressions of executive summary report don't support the 'group by' feature."))
date_to = fields.Date.from_string(options['date']['date_to'])
# in 'single' date mode, uses the company's fiscal-year start date
date_from = (
fields.Date.from_string(options["date"]["date_from"])
or self.env.company.compute_fiscalyear_dates(date_to)["date_from"]
)
return {next(iter(formulas_dict.values())): {'result': (date_to - date_from).days + 1, 'has_sublines': False}}

View File

@@ -0,0 +1,247 @@
from odoo import models
from odoo.addons.account_reports.utils.report_data_objects import AccountReportColumnFormatParamsData
from odoo.tools import SQL
import json
GROUPED_ACCOUNT_TYPES = {
'receivable': {'types': ('asset_receivable',), 'counterpart': 'payable'},
'payable': {'types': ('liability_payable',), 'counterpart': 'receivable'},
'current_assets': {'types': ('asset_current', 'asset_prepayments'), 'counterpart': 'current_liabilities'},
'current_liabilities': {'types': ('liability_current', 'liability_credit_card'), 'counterpart': 'current_assets'},
'income': {'types': ('income', 'income_other'), 'counterpart': 'expense'},
'expense': {'types': ('expense', 'expense_other', 'expense_depreciation', 'expense_direct_cost'), 'counterpart': 'income'},
'non_current_assets': {'types': ('asset_fixed', 'asset_non_current'), 'counterpart': 'equity_and_non_cur_liabilities'},
'equity_and_non_cur_liabilities': {'types': ('equity', 'equity_unaffected', 'liability_non_current'), 'counterpart': 'non_current_assets'},
'liquidity': {'types': ('asset_cash',), 'counterpart': 'liquidity'},
'off_balance': {'types': ('off_balance',), 'counterpart': 'off_balance'},
}
class IntercoComparisonReportHandler(models.AbstractModel):
_name = 'account.interco.comparison.report.handler'
_inherit = ['account.report.custom.handler']
_description = "Interco Comparison Report Custom Handler"
def _custom_options_initializer(self, report, options, previous_options):
main_company_col_opt = next((col_opt for col_opt in options['columns'] if col_opt['expression_label'] == 'main_company'), {})
main_company_col_opt['name'] = self.env.company.name
options['ignore_totals_below_sections'] = True
companies = self.env['res.company'].browse(report.get_report_company_ids(options))
counterpart_companies = companies - self.env.company
options['forced_domain'] = [
*options.get('forced_domain', []),
('move_id.exchange_diff_partial_ids', '=', False),
'|',
'&', ('partner_id', 'in', counterpart_companies.partner_id.ids), ('company_id', '=', self.env.company.id),
'&', ('partner_id', '=', self.env.company.partner_id.id), ('company_id', 'in', counterpart_companies.ids),
]
options['hide_tax_lines'] = (previous_options or {}).get('hide_tax_lines', True)
if options['hide_tax_lines']:
options['forced_domain'].append(('tax_line_id', '=', False))
options['custom_display_config'] = {
'components': {
'AccountReportFilters': 'IntercoComparisonReportFilters',
},
}
def _customize_warnings(self, report, options, all_column_groups_expression_totals, warnings):
if len(options['companies']) == 1:
warnings['account_reports.interco_comparison_single_company_warning'] = {'alert_type': 'warning'}
def _report_engine_interco_comparison(self, options, date_scope, formulas_dict, current_groupby, warnings=None):
report = self.env['account.report'].browse(options['report_id'])
if current_groupby:
report._check_groupby_fields([current_groupby])
else:
return {next(iter(formulas_dict.values())): {'has_sublines': True, 'main_company': None, 'counterpart': None, 'difference': None}}
query = report._get_report_query(options, date_scope)
aml_table = query.table._sudo()
if current_groupby == 'interco_company':
aml_company_table = aml_table._join('company_id')
query.groupby = SQL(
"""
CASE WHEN %(company_id_field)s = %(main_company_id)s THEN %(partner_id_field)s
ELSE %(company_partner_field)s
END
""",
company_id_field=aml_table.company_id,
main_company_id=self.env.company.id,
partner_id_field=aml_table.partner_id,
company_partner_field=aml_company_table.partner_id,
)
elif current_groupby == 'interco_account_type':
groupby_sql_parts = []
for grouping_key, grouping_rule in GROUPED_ACCOUNT_TYPES.items():
groupby_sql_parts.append(SQL(
"WHEN %(company_id_field)s = %(main_company_id)s AND %(account_type_field)s IN %(account_types)s THEN %(grouping_key)s",
company_id_field=aml_table.company_id,
main_company_id=self.env.company.id,
account_type_field=aml_table.account_type,
account_types=grouping_rule['types'],
grouping_key=grouping_key,
))
groupby_sql_parts.append(SQL(
"WHEN %(company_id_field)s != %(main_company_id)s AND %(account_type_field)s IN %(account_types)s THEN %(grouping_key)s",
company_id_field=aml_table.company_id,
main_company_id=self.env.company.id,
account_type_field=aml_table.account_type,
account_types=GROUPED_ACCOUNT_TYPES[grouping_rule['counterpart']]['types'],
grouping_key=grouping_key,
))
query.groupby = SQL(
"""
CASE
%(groupby_parts)s
ELSE 'unknown'
END
""",
groupby_parts=SQL('\n').join(groupby_sql_parts),
)
elif current_groupby == 'interco_account':
aml_account_table = aml_table._join('account_id')
query.groupby = SQL(
"""
JSON_BUILD_OBJECT(
'account_id', %(account_id_field)s,
'code', COALESCE(%(account_table)s.code_store->>%(company_id_field)s::VARCHAR),
'name', %(account_name_field)s,
'company_id', %(company_id_field)s
)::VARCHAR
""",
account_id_field=aml_table.account_id,
account_table=aml_account_table,
account_name_field=aml_account_table.name,
company_id_field=aml_table.company_id,
)
else:
query.groupby = aml_table[current_groupby]
sql = query.select(SQL(
"""
%(grouping_key)s AS grouping_key,
SUM(CASE WHEN %(company_field)s = %(main_company_id)s THEN %(amount_currency_field)s ELSE 0 END) AS main_company_amount,
SUM(CASE WHEN %(company_field)s != %(main_company_id)s THEN %(amount_currency_field)s ELSE 0 END) AS counterpart_amount
""",
grouping_key=query.groupby,
company_field=aml_table.company_id,
main_company_id=self.env.company.id,
amount_currency_field=aml_table.amount_currency,
))
rslt = []
for query_res in self.env.execute_query_dict(sql):
main_company_amount = query_res['main_company_amount']
counterpart_amount = query_res['counterpart_amount']
rslt.append((
query_res['grouping_key'],
{'has_sublines': True, 'main_company': main_company_amount, 'counterpart': counterpart_amount, 'difference': main_company_amount + counterpart_amount},
))
return {next(iter(formulas_dict.values())): rslt}
def _custom_groupby_line_completer(self, report, options, line_data, current_groupby):
if current_groupby in ('currency_id', 'interco_company'):
line_data.unfolded = True
def _custom_line_postprocessor(self, report, options, lines):
for line in lines:
related_currency_id = report._get_res_id_from_line_id(line.id, 'res.currency')
related_currency = self.env['res.currency'].browse(related_currency_id)
for col_data in line.columns:
col_data.format_params = AccountReportColumnFormatParamsData(digits=related_currency.decimal_places)
if not col_data.is_zero:
col_data.css_class = ' ' # Makes sure negative amounts aren't displayed in red (no style is applied when the css_class key is set)
return lines
def _get_custom_groupby_map(self):
def interco_company_domain_builder(grouping_key):
return [
'|',
'&', ('company_id', '=', self.env.company.id), ('partner_id', '=', grouping_key),
'&', ('company_id', '!=', self.env.company.id), ('company_id.partner_id', '=', grouping_key),
]
def interco_account_type_domain_builder(grouping_key):
grouped_acc_type = GROUPED_ACCOUNT_TYPES[grouping_key]
counterpart_acc_type = GROUPED_ACCOUNT_TYPES[grouped_acc_type['counterpart']]
return [
'|',
'&', ('company_id', '=', self.env.company.id), ('account_type', 'in', grouped_acc_type['types']),
'&', ('company_id', '!=', self.env.company.id), ('account_type', 'in', counterpart_acc_type['types']),
]
def interco_account_type_label_builder(grouping_keys):
key_labels = {
'receivable': self.env._("Receivable"),
'payable': self.env._("Payable"),
'current_assets': self.env._("Current Assets"),
'current_liabilities': self.env._("Current Liabilities"),
'income': self.env._("Income"),
'expense': self.env._("Expense"),
'non_current_assets': self.env._("Non-current Assets"),
'equity_and_non_cur_liabilities': self.env._("Equity & Non-current Liabilities"),
'liquidity': self.env._("Liquidity"),
'off_balance': self.env._("Off-balance"),
'unknown': self.env._("Unknown"),
}
keys_with_label = [(key, key_labels[key]) for key in grouping_keys]
return dict(sorted(keys_with_label, key=lambda x: x[1]))
def interco_account_label_builder(grouping_keys):
company_names = {company.id: company.name for company in self.env.companies}
keys_and_labels = []
for key in grouping_keys:
parsed_key = json.loads(key)
label = f"{parsed_key['code'] or ''} {parsed_key['name']} ({company_names[parsed_key['company_id']]})".strip()
keys_and_labels.append((key, label))
return dict(sorted(keys_and_labels, key=lambda x: x[1]))
def interco_account_domain_builder(grouping_key):
parsed_key = json.loads(grouping_key)
return [('company_id', '=', parsed_key['company_id']), ('account_id', '=', parsed_key['account_id'])]
return {
'interco_company': {
'model': 'res.partner',
'domain_builder': interco_company_domain_builder,
},
'interco_account_type': {
'model': None,
'domain_builder': interco_account_type_domain_builder,
'label_builder': interco_account_type_label_builder,
},
'interco_account': {
'model': None,
'label_builder': interco_account_label_builder,
'domain_builder': interco_account_domain_builder,
},
}
def action_audit_cell(self, options, params):
expression_label = params.get('expression_label')
if expression_label == 'main_company':
options.setdefault('forced_domain', []).append(('company_id', '=', self.env.company.id))
elif expression_label == 'counterpart':
options.setdefault('forced_domain', []).append(('company_id', '!=', self.env.company.id))
report = self.env['account.report'].browse(options['report_id'])
return report.action_audit_cell(options, params)

View File

@@ -0,0 +1,21 @@
# -*- coding: utf-8 -*-
from odoo import models
class Ir_Actions_Account_Report_Download(models.AbstractModel):
# This model is a a hack: it's sole purpose is to override _get_readable_fields
# of ir.actions.actions to add the 'data' field which, as explained below, contains the
# necessary parameters for report generation.
# The reason why we don't extend the ir.actions.actions is because it's not really meant to be
# extended outside of the base module, the risk being completely destroying the client's db.
# If you plan on modifying this model, think of reading odoo/enterprise#13820 and/or contact
# the metastorm team.
_name = 'ir_actions_account_report_download'
_description = 'Technical model for accounting report downloads'
def _get_readable_fields(self):
# data is not a stored field, but is used to give the parameters to generate the report
# We keep it this way to ensure compatibility with the way former version called this action.
return self.env['ir.actions.actions']._get_readable_fields() | {'data'}

View File

@@ -0,0 +1,17 @@
import datetime
from dateutil.relativedelta import relativedelta
from odoo import models
class IrModuleModule(models.Model):
_inherit = "ir.module.module"
def _load_module_terms(self, modules, langs, overwrite=False):
super()._load_module_terms(modules, langs, overwrite=overwrite)
if not langs or langs == ['en_US'] or not modules or 'account_reports' not in modules:
return
for lang in langs:
self.env['account.return'].search([
('date_to', '>=', datetime.date.today() - relativedelta(years=1),
)]).with_context({'update_returns_translation_lang': lang})._update_translated_name()

View File

@@ -0,0 +1,13 @@
from odoo import models
class IrUiMenu(models.Model):
_inherit = 'ir.ui.menu'
def _get_account_readonly_menu_ids(self):
res = super()._get_account_readonly_menu_ids()
res.extend([
'account_reports.menu_action_account_report_multicurrency_revaluation',
'account_reports.menu_action_account_report_tree',
])
return res

View File

@@ -0,0 +1,141 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from collections import defaultdict
from datetime import datetime
import re
from odoo import api, models
from odoo.tools import SQL
class KpiProvider(models.AbstractModel):
_inherit = 'kpi.provider'
@api.model
def get_account_reports_kpi_summary(self):
return get_kpi_summary(self.env.cr, self.env.uid)
@api.model
def get_kpi_summary(self):
result = super().get_kpi_summary()
result.extend(self.get_account_reports_kpi_summary())
return result
def _tax_return_grouping_key(external_ids, return_info):
external_id = ''
# Determine the external identifier used to categorize the tax returns:
# - use the identifier of the root report if any,
# - otherwise use the identifier of the report,
# - otherwise use the identifier of the return type.
external_id = external_ids.get(('account.report', return_info['root_report_id']))
if not external_id:
external_id = external_ids.get(('account.report', return_info['report_id']))
if not external_id:
external_id = external_ids.get(('account.return.type', return_info['return_type_id']))
if not external_id:
external_id = return_info['tax_return_name']
# Special case for l10n_eu_oss_reports.* that are all merged together.
if external_id.startswith('l10n_eu_oss_reports.'):
external_id = 'l10n_eu_oss_reports'
# property names must match odoo.orm.utils.regex_alphanumeric
return re.sub(r'[^a-z0-9_]', '_', external_id.lower())
def _tax_returns_get_value(tax_returns):
for tax_return in tax_returns:
if tax_return['is_late']:
return 'late'
elif not tax_return['is_completed']:
if tax_return['state'] in ('reviewed', 'submitted'):
return 'to_submit'
elif tax_return['in_next_3_months']:
return 'to_do'
else:
return 'longterm'
return 'done'
def get_kpi_summary(cr, uid):
"""
Retrieve the status of pending tax returns grouped by report or return type.
The returned KPIs include:
- overdue tax returns;
- upcoming tax returns within the next 3 months;
- completion state of each tax return group.
This function intentionally bypasses the ORM so KPI summaries can be retrieved
without loading a registry, allowing multi-database servers to serve them faster.
"""
expected_columns = {
'account_return.date_deadline',
'account_return.is_completed',
'account_return.type_id',
'account_return_type.report_id',
'account_report.root_report_id',
}
cr.execute(SQL("""
SELECT table_name || '.' || column_name
FROM information_schema.columns
WHERE table_name || '.' || column_name IN %(columns)s
""", columns=tuple(expected_columns)))
existing_columns = {x[0] for x in cr.fetchall()}
if expected_columns - existing_columns:
# Needed columns are not present -> module is not installed
return []
cr.execute(SQL("""
SELECT model, res_id, module || '.' || name
FROM ir_model_data
WHERE model IN ('account.report', 'account.return.type')
AND module != '__export__'
"""))
external_ids = {
(model, res_id): complete_name
for model, res_id, complete_name in cr.fetchall()
}
now = datetime.now() # Using python-generated dates to respect what freezegun has frozen in tests
cr.execute(SQL("""
SELECT return.id return_id,
type.id return_type_id,
report.id report_id,
root_report.id root_report_id,
COALESCE(report.name->>partner.lang,
report.name->>'en_US',
type.name->>partner.lang,
type.name->>'en_US') tax_return_name,
return.date_deadline <= (%(now)s AT TIME ZONE COALESCE(partner.tz, 'UTC'))::date is_late,
return.date_deadline <= (%(now)s AT TIME ZONE COALESCE(partner.tz, 'UTC'))::date + INTERVAL '3 months' in_next_3_months,
return.is_completed,
return.state
FROM account_return return
JOIN res_users u ON u.id = %(uid)s
JOIN res_partner partner ON partner.id = u.partner_id
JOIN account_return_type type ON return.type_id = type.id
LEFT JOIN account_report report ON type.report_id = report.id
LEFT JOIN account_report root_report ON report.root_report_id = root_report.id
WHERE return.active
AND (
NOT return.is_completed
OR return.date_deadline >= (%(now)s AT TIME ZONE COALESCE(partner.tz, 'UTC'))::date
)
ORDER BY return.date_deadline NULLS LAST, return.id
""",
uid=uid,
now=now,
))
returns_by_external_id = defaultdict(list)
for return_info in cr.dictfetchall():
key = _tax_return_grouping_key(external_ids, return_info)
returns_by_external_id[key].append(return_info)
return [{
'id': f'account_return.{external_id}',
'name': tax_returns[0]['tax_return_name'],
'type': 'return_status',
'value': _tax_returns_get_value(tax_returns),
} for external_id, tax_returns in returns_by_external_id.items()]

View File

@@ -0,0 +1,13 @@
from odoo import models
class MailActivity(models.Model):
_inherit = 'mail.activity'
def action_open_document(self):
# OVERRIDE
# when opening the "View all activities", and opening a return, we actually want the kanban view of return checks
if self.res_model != 'account.return':
return super().action_open_document()
return self.env['account.return'].browse(self.res_id).action_open_account_return()

View File

@@ -0,0 +1,25 @@
from odoo import models
from odoo.addons.mail.tools.discuss import Store
class MailMessage(models.Model):
_inherit = 'mail.message'
def _store_message_fields(self, res: Store.FieldList, **kwargs):
super()._store_message_fields(res, **kwargs)
if not self.env["account.report.annotation"].has_access("read"):
return
annotable_models = self.env["account.report"]._get_annotatable_models()
if annotable_messages := self.filtered(lambda m: m.model in annotable_models):
message_to_annotation_date = {
annotation.message_id: annotation.date
for annotation in self.env["account.report.annotation"].search_fetch(
[("message_id", "in", annotable_messages.ids)]
)
}
res.attr(
"account_reports_annotation_date",
value=message_to_annotation_date.get,
predicate=lambda m: m in annotable_messages,
)

View File

@@ -0,0 +1,19 @@
from odoo import fields, models
class MailScheduledMessage(models.Model):
_inherit = 'mail.scheduled.message'
account_reports_annotation_date = fields.Date("Annotated For")
def _message_created_hook(self, message):
"""Hook called when a message is created from the scheduled message.
:param record message: the created mail.message record
"""
super()._message_created_hook(message)
if self.account_reports_annotation_date:
self.env['account.report.annotation'].with_user(self.create_uid).create({
'date': self.account_reports_annotation_date,
'message_id': message.id,
})

View File

@@ -0,0 +1,27 @@
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import models
class MailThread(models.AbstractModel):
_name = "mail.thread"
_inherit = ["mail.thread"]
def _message_post_after_hook(self, message):
if self._name in self.env["account.report"]._get_annotatable_models() and (
annotation_date := self.env.context.get("account_reports_annotation_date")
):
self.env["account.report.annotation"].create(
{"message_id": message.id, "date": annotation_date}
)
return super()._message_post_after_hook(message)
def _message_update_content(self, message, /, *, body, **kwargs):
super()._message_update_content(message, body=body, **kwargs)
if (
self._name in self.env["account.report"]._get_annotatable_models()
and message._filter_empty()
):
self.env["account.report.annotation"].sudo().search(
[("message_id", "=", message.id)]
).unlink()

View File

@@ -0,0 +1,23 @@
from odoo import models
class AccountProfitAndLossReportHandler(models.AbstractModel):
_name = 'account.profit.and.loss.report.handler'
_inherit = ['account.report.custom.handler']
_description = "Profit And Loss Custom Handler"
def action_audit_cell(self, options, params):
report = self.env['account.report'].browse(options['report_id'])
action = report.action_audit_cell(options, params)
if options.get('multi_currency'):
date_from, date_to = report._get_date_bounds_info(options, 'strict_range')
action['context'].update({
'currency_translation': report.currency_translation,
'date_from': date_from,
'date_to': date_to,
})
action['views'] = [(self.env.ref('account_reports.view_multi_currency_report_audit').id, 'list')]
return action

View File

@@ -0,0 +1,251 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import datetime
from dateutil.relativedelta import relativedelta
from odoo import api, fields, models
from odoo.fields import Domain
from ..models.account_return import PERIODS
class ResCompany(models.Model):
_inherit = "res.company"
totals_below_sections = fields.Boolean(
compute='_compute_totals_below_sections', store=True,
string='Add totals below sections',
help='When ticked, totals and subtotals appear below the sections of the report.',
readonly=False)
account_reports_negative_format = fields.Selection(
selection=[
('parentheses', '(100)'),
('minus_before', '-100'),
],
default='minus_before',
string='Negative amount display',
)
account_return_periodicity = fields.Selection(
selection=PERIODS,
string="Delay units",
help="Periodicity",
required=True,
default="monthly"
)
account_return_reminder_day = fields.Integer(string='Start from', default=7, required=True)
account_tax_return_journal_id = fields.Many2one(
comodel_name='account.journal',
string='Journal',
domain=[('type', '=', 'general')],
check_company=True,
)
account_revaluation_journal_id = fields.Many2one('account.journal', domain=[('type', '=', 'general')], check_company=True)
account_revaluation_expense_provision_account_id = fields.Many2one('account.account', string='Expense Provision Account', check_company=True)
account_revaluation_income_provision_account_id = fields.Many2one('account.account', string='Income Provision Account', check_company=True)
account_tax_unit_ids = fields.Many2many(string="Tax Units", comodel_name='account.tax.unit', help="The tax units this company belongs to.")
account_representative_id = fields.Many2one('res.partner', string='Accounting Firm', index='btree_not_null',
help="Specify an Accounting Firm that will act as a representative when exporting reports.")
account_display_representative_field = fields.Boolean(compute='_compute_account_display_representative_field')
account_last_return_cron_refresh = fields.Datetime()
@api.depends('account_fiscal_country_id.code')
def _compute_account_display_representative_field(self):
country_set = self._get_countries_allowing_tax_representative()
for record in self:
record.account_display_representative_field = record.account_fiscal_country_id.code in country_set
@api.depends('anglo_saxon_accounting')
def _compute_totals_below_sections(self):
for company in self:
company.totals_below_sections = company.anglo_saxon_accounting
def _inverse_vat_disabled(self):
super()._inverse_vat_disabled()
for company in self.filtered(lambda c: c.vat_disabled_available):
company.account_tax_return_journal_id.show_on_dashboard = not (company.account_opening_date and company.vat_disabled)
company._toggle_account_reports_on_vat_disabled()
company._toggle_account_return_types_on_vat_disabled()
def _toggle_account_reports_on_vat_disabled(self, reports=None):
self.ensure_one()
vat_reports = self._get_vat_enabled_account_reports()
reports_to_toggle = vat_reports if reports is None else reports & vat_reports
if reports_to_toggle:
reports_to_toggle.with_company(self).active_selection = 'False' if self.vat_disabled else 'True'
def _toggle_account_return_types_on_vat_disabled(self, return_types=None):
self.ensure_one()
vat_returns = self._get_vat_enabled_account_return_types()
returns_to_toggle = vat_returns if return_types is None else return_types & vat_returns
if returns_to_toggle:
returns_to_toggle.with_company(self).active_selection = 'False' if self.vat_disabled else 'True'
def _get_vat_enabled_account_reports(self):
"""
Returns the tax reports that needs to be toggled (activate / deactivate ) when VAT is enabled / disabled.
"""
self.ensure_one()
ec_sales_report = self.env.ref('account_reports.generic_ec_sales_report', raise_if_not_found=False) or self.env['account.report']
generic_tax_report = self.env.ref('account.generic_tax_report', raise_if_not_found=False) or self.env['account.report']
vat_reports = ec_sales_report | generic_tax_report
if not vat_reports:
return self.env['account.report']
return self.env['account.report'].with_context(active_test=False).search([
'|',
('root_report_id', 'in', vat_reports.ids),
('id', 'in', vat_reports.ids),
])
def _get_vat_enabled_account_return_types(self):
"""
Returns the return types that needs to be toggled (activate / deactivate ) when VAT is enabled / disabled.
This function is a hook that needs to be overridden in localisation modules.
"""
self.ensure_one()
return self.env['account.return.type']
def _get_countries_allowing_tax_representative(self):
""" Returns a set containing the country codes of the countries for which
it is possible to use a representative to submit the tax report.
This function is a hook that needs to be overridden in localisation modules.
"""
return set()
def _get_tax_closing_journal(self):
if not self.account_tax_return_journal_id:
closing_journal = self.env['account.journal']
for company in reversed(self.sudo().parent_ids):
if journal := company.account_tax_return_journal_id:
closing_journal = journal
break
if not closing_journal:
closing_journal = self.env['account.journal'].sudo().search([
*self.env['account.journal']._check_company_domain(self),
('code', 'in', ('TAX', 'TRTRN')), # TRTRN for Backward compatibility
('type', '=', 'general'),
], limit=1)
if not closing_journal:
# Try reloading the chart template data to create the tax return journal with translations.
ChartTemplate = self.env['account.chart.template'].with_company(self)
ChartTemplate._load_data({
'account.journal': ChartTemplate._get_account_reports_journal(self.chart_template),
'res.company': ChartTemplate._get_account_reports_res_company(self.chart_template),
})
closing_journal = ChartTemplate.ref('tax_returns')
self.account_tax_return_journal_id = closing_journal
return self.account_tax_return_journal_id
@api.model_create_multi
def create(self, vals_list):
companies = super().create(vals_list)
companies._initiate_account_onboardings()
# Set default values on every return types for this new company
return_types = self.env['account.return.type'].sudo().search([
'|',
('deadline_periodicity', '=', False),
('deadline_start_date', '=', False),
])
return_types._set_default_values(companies)
self.env['account.return.type'].sudo()._generate_or_refresh_all_returns(companies.root_id)
return companies
def write(self, vals):
root_companies_before = self.root_id
res = super().write(vals)
roots_to_recompute = root_companies_before | self.root_id
if 'account_opening_date' in vals:
self.env['account.return.type'].with_context(
# 2 years to make sure we cover all cases, such as yearly returns with a deadline of more than 1 year.
forced_date_from=self.account_opening_date - relativedelta(years=2),
forced_date_to=datetime.date.today(),
)._generate_or_refresh_all_returns(roots_to_recompute)
elif set(vals) & {'account_return_periodicity', 'account_return_reminder_day', 'child_ids', 'parent_id'} and self.account_opening_date:
self.env['account.return.type']._generate_or_refresh_all_returns(roots_to_recompute)
if any(lock_date_field in vals for lock_date_field in ('fiscalyear_lock_date', 'hard_lock_date', 'tax_lock_date')):
self.env.ref('account_reports.ir_cron_garbage_collect_snapshots')._trigger()
# Skip returns whose deadline is determined by the return type's 'deadline_days_delay',
# because changes to the company's 'account_return_reminder_day' do not affect their computed deadline.
if 'account_return_reminder_day' in vals:
domain = Domain.FALSE
for company in self:
return_types = self.env['account.return.type'].with_company(company).search([
('deadline_days_delay', '=', 0),
])
if return_types:
domain |= Domain([
('company_id', '=', company.id),
('is_completed', '=', False),
('type_id', 'in', return_types.ids),
])
if domain:
account_returns = self.env['account.return'].search(domain)
if account_returns:
account_returns._compute_deadline()
return res
def _get_available_tax_units(self, report, limit=None):
"""
:return: A recordset of available tax units for this report and this company
"""
self.ensure_one()
return self.env['account.tax.unit'].search([
('company_ids', 'in', self.id),
('country_id', '=', report.country_id.id),
], limit=limit)
def _get_branches_with_same_vat(self, accessible_only=False):
""" Returns all companies among self and its branch hierachy (considering children and parents) that share the same VAT number
as self. An empty VAT number is considered as being the same as the one of the closest parent with a VAT number.
self is always returned as the first element of the resulting recordset (so that this can safely be used to restore the active company).
Example::
- main company ; vat = 123
- branch 1
- branch 1_1
- branch 2 ; vat = 456
- branch 2_1 ; vat = 789
- branch 2_2
In this example, the following VAT numbers will be considered for each company::
- main company: 123
- branch 1: 123
- branch 1_1: 123
- branch 2: 456
- branch 2_1: 789
- branch 2_2: 456
:param accessible_only: whether the returned companies should exclude companies that are not in self.env.companies
"""
self.ensure_one()
current = self.sudo()
same_vat_branch_ids = [current.id] # Current is always available
current_strict_parents = current.parent_ids - current
if accessible_only:
candidate_branches = current.root_id._accessible_branches()
else:
candidate_branches = self.env['res.company'].sudo().search([('id', 'child_of', current.root_id.ids)])
current_vat_check_set = {current.vat} if current.vat else set()
for branch in candidate_branches - current:
parents_vat_set = set(filter(None, (branch.parent_ids - current_strict_parents).mapped('vat')))
if parents_vat_set == current_vat_check_set:
# If all the branches between the active company and branch (both included) share the same VAT number as the active company,
# we want to add the branch to the selection.
same_vat_branch_ids.append(branch.id)
return self.browse(same_vat_branch_ids)

View File

@@ -0,0 +1,25 @@
from odoo import fields, models
class ResConfigSettings(models.TransientModel):
_inherit = 'res.config.settings'
totals_below_sections = fields.Boolean(related='company_id.totals_below_sections', string='Add totals below sections', readonly=False,
help='When ticked, totals and subtotals appear below the sections of the report.')
account_reports_negative_format = fields.Selection(
related='company_id.account_reports_negative_format',
string='Negative amount display',
readonly=False,
)
account_return_periodicity = fields.Selection(related='company_id.account_return_periodicity', string='Periodicity', readonly=False, required=True)
account_return_reminder_day = fields.Integer(related='company_id.account_return_reminder_day', string='Deadline', readonly=False, required=True)
account_tax_return_journal_id = fields.Many2one(related='company_id.account_tax_return_journal_id', string='Journal', readonly=False)
def open_tax_return_type_list(self):
self.ensure_one()
action = self.env['ir.actions.actions']._for_xml_id('account_reports.action_view_account_return_types')
action['domain'] = [
('category', '=', 'account_return'),
'|', ('is_country_in_active_country', '=', True), ('country_id', '=', False),
]
return action

View File

@@ -0,0 +1,102 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from odoo import api, fields, models, _
class ResPartner(models.Model):
_inherit = 'res.partner'
account_represented_company_ids = fields.One2many('res.company', 'account_representative_id')
def _get_followup_responsible(self, multiple_responsible=False, *, followup_line=None):
return self.env.user
def open_customer_statement(self):
action = self.env["ir.actions.actions"]._for_xml_id("account_reports.action_account_report_customer_statement")
action['params'] = {
'options': {
'partner_ids': (self | self.commercial_partner_id).ids,
'unfold_all': len(self.ids) == 1,
},
'ignore_session': True,
}
return action
def open_follow_up_report(self):
action = self.env["ir.actions.actions"]._for_xml_id("account_reports.action_account_report_followup")
action['params'] = {
'options': {
'partner_ids': (self | self.commercial_partner_id).ids,
'unfold_all': len(self.ids) == 1,
},
'ignore_session': True,
}
return action
def open_partner(self):
return {
'type': 'ir.actions.act_window',
'res_model': 'res.partner',
'res_id': self.id,
'views': [[False, 'form']],
'view_mode': 'form',
'target': 'current',
}
@api.depends_context('show_more_partner_info')
def _compute_display_name(self):
if not self.env.context.get('show_more_partner_info'):
return super()._compute_display_name()
for partner in self:
res = ""
if partner.has_vat:
res += f" {partner.vat},"
if partner.country_id:
res += f" {partner.country_id.code},"
partner.display_name = f"{partner.name} - " + res
def _get_partner_account_report_attachment(self, report, options=None):
self.ensure_one()
if self.lang:
# Print the followup in the customer's language
report = report.with_context(lang=self.lang)
if not options:
options = report.get_options({
'forced_companies': self.env.company.search([('id', 'child_of', self.env.context.get('allowed_company_ids', self.env.company.id))]).ids,
'partner_ids': self.ids,
'unfold_all': True,
'unreconciled': True,
'all_entries': False,
})
attachment_file = report.export_to_pdf(options)
file_name = report.get_default_partner_report_filename(self, options)
return self.env['ir.attachment'].create([
{
'name': file_name,
'res_model': self._name,
'res_id': self.id,
'type': 'binary',
'raw': attachment_file['file_content'],
'mimetype': 'application/pdf',
},
])
def set_commercial_partner_main(self):
self.ensure_one()
main_partner = self
duplicated_partners = self.env['res.partner'].search([
('vat', '=', main_partner.vat),
('id', '!=', main_partner.id)
])
# Update commercial partner of all duplicates
duplicated_partners.write({
'parent_id': main_partner.id,
'type': 'invoice',
})
duplicate_partners_vat = self.env.context.get('duplicate_partners_vat', [])
remaining_vats = [pvat for pvat in duplicate_partners_vat if pvat != main_partner.vat]
return self.env['account.ec.sales.report.handler.common']._get_duplicate_vat_partners(remaining_vats)

View File

@@ -0,0 +1,23 @@
from odoo import api, models, modules
class ResUsers(models.Model):
_inherit = 'res.users'
@api.model
def _get_activity_groups(self):
activities = super()._get_activity_groups()
activity_names = {
'account.return': self.env._("Tax Returns"),
'account.return.check': self.env._("Tax Return Checks"),
}
for activity in activities:
if name := activity_names.get(activity['model']):
activity |= {
'name': name,
'icon': modules.module.get_module_icon('accountant'),
'view_type': 'kanban',
}
return activities