初始提交

This commit is contained in:
2026-11-04 19:58:07 +08:00
commit 53b7d22429
829 changed files with 469986 additions and 0 deletions

View File

@@ -0,0 +1,9 @@
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
from . import account_change_lock_date
from . import account_auto_reconcile_wizard
from . import account_reconcile_wizard
from . import account_select_account_line
from . import account_split_journal_item_wizard
from . import bank_rec_auto_reconcile_wizard

View File

@@ -0,0 +1,176 @@
from datetime import date
from odoo import api, Command, fields, models, _
from odoo.exceptions import UserError
class AccountAutoReconcileWizard(models.TransientModel):
""" This wizard is used to automatically reconcile account.move.line.
It is accessible trough Accounting > Accounting tab > Actions > Auto-reconcile menuitem.
"""
_name = 'account.auto.reconcile.wizard'
_description = 'Account automatic reconciliation wizard'
_check_company_auto = True
company_id = fields.Many2one(
comodel_name='res.company',
required=True,
readonly=True,
default=lambda self: self.env.company,
)
line_ids = fields.Many2many(comodel_name='account.move.line') # Amls from which we derive a preset for the wizard
from_date = fields.Date(string='From')
to_date = fields.Date(string='To', default=fields.Date.context_today, required=True)
account_ids = fields.Many2many(
comodel_name='account.account',
string='Accounts',
check_company=True,
domain="[('reconcile', '=', True), ('account_type', '!=', 'off_balance')]",
)
partner_ids = fields.Many2many(
comodel_name='res.partner',
string='Partners',
check_company=True,
domain="[('company_id', 'in', (False, company_id)), '|', ('parent_id', '=', False), ('is_company', '=', True)]",
)
search_mode = fields.Selection(
selection=[
('one_to_one', "Perfect Match"),
('zero_balance', "Clear Account"),
],
string='Reconcile',
required=True,
default='one_to_one',
help="Reconcile journal items with opposite balance or clear accounts with a zero balance",
)
@api.model
def default_get(self, fields):
res = super().default_get(fields)
domain = self.env.context.get('domain')
if 'line_ids' in fields and 'line_ids' not in res and domain:
amls = self.env['account.move.line'].search(domain)
if amls:
# pre-configure the wizard
res.update(self._get_default_wizard_values(amls))
res['line_ids'] = [Command.set(amls.ids)]
return res
@api.model
def _get_default_wizard_values(self, amls):
""" Derive a preset configuration based on amls.
For example if all amls have the same account_id we will set it in the wizard.
:param amls: account move lines from which we will derive a preset
:return: a dict with preset values
"""
return {
'account_ids': [Command.set(amls[0].account_id.ids)] if all(aml.account_id == amls[0].account_id for aml in amls) else [],
'partner_ids': [Command.set(amls[0].partner_id.ids)] if all(aml.partner_id == amls[0].partner_id for aml in amls) else [],
'search_mode': 'zero_balance' if amls.company_currency_id.is_zero(sum(amls.mapped('balance'))) else 'one_to_one',
'from_date': min(amls.mapped('date')),
'to_date': max(amls.mapped('date')),
}
def _get_wizard_values(self):
""" Get the current configuration of the wizard as a dict of values.
:return: a dict with the current configuration of the wizard.
"""
self.ensure_one()
return {
'account_ids': [Command.set(self.account_ids.ids)] if self.account_ids else [],
'partner_ids': [Command.set(self.partner_ids.ids)] if self.partner_ids else [],
'search_mode': self.search_mode,
'from_date': self.from_date,
'to_date': self.to_date,
}
# ==== Business methods ====
def _get_amls_domain(self):
""" Get the domain of amls to be auto-reconciled. """
self.ensure_one()
if self.line_ids and self._get_wizard_values() == self._get_default_wizard_values(self.line_ids):
domain = [('id', 'in', self.line_ids.ids)]
else:
domain = [
('company_id', '=', self.company_id.id),
('parent_state', '=', 'posted'),
('display_type', 'not in', ('line_section', 'line_subsection', 'line_note')),
('date', '>=', self.from_date or date.min),
('date', '<=', self.to_date),
('reconciled', '=', False),
('account_id.reconcile', '=', True),
('amount_residual_currency', '!=', 0.0),
('amount_residual', '!=', 0.0), # excludes exchange difference lines
]
if self.account_ids:
domain.append(('account_id', 'in', self.account_ids.ids))
if self.partner_ids:
domain.append(('partner_id', 'in', self.partner_ids.ids))
return domain
def _auto_reconcile_one_to_one(self):
""" Auto-reconcile with one-to-one strategy:
We will reconcile 2 amls together if their combined balance is zero.
:return: a recordset of reconciled amls
"""
grouped_amls_data = self.env['account.move.line']._read_group(
self._get_amls_domain(),
['account_id', 'partner_id', 'currency_id', 'amount_residual_currency:abs_rounded'],
['id:recordset'],
)
all_reconciled_amls = self.env['account.move.line']
amls_grouped_by_2 = [] # we need to group amls with right format for _reconcile_plan
for *__, grouped_aml_ids in grouped_amls_data:
positive_amls = grouped_aml_ids.filtered(lambda aml: aml.amount_residual_currency >= 0).sorted('date')
negative_amls = (grouped_aml_ids - positive_amls).sorted('date')
min_len = min(len(positive_amls), len(negative_amls))
positive_amls = positive_amls[:min_len]
negative_amls = negative_amls[:min_len]
all_reconciled_amls += positive_amls + negative_amls
amls_grouped_by_2 += [pos_aml + neg_aml for (pos_aml, neg_aml) in zip(positive_amls, negative_amls)]
self.env['account.move.line']._reconcile_plan(amls_grouped_by_2)
return all_reconciled_amls
def _auto_reconcile_zero_balance(self):
""" Auto-reconcile with zero balance strategy:
We will reconcile all amls grouped by currency/account/partner that have a total balance of zero.
:return: a recordset of reconciled amls
"""
grouped_amls_data = self.env['account.move.line']._read_group(
self._get_amls_domain(),
groupby=['account_id', 'partner_id', 'currency_id'],
aggregates=['id:recordset'],
having=[('amount_residual_currency:sum_rounded', '=', 0)],
)
all_reconciled_amls = self.env['account.move.line']
amls_grouped_together = [] # we need to group amls with right format for _reconcile_plan
for aml_data in grouped_amls_data:
all_reconciled_amls += aml_data[-1]
amls_grouped_together += [aml_data[-1]]
self.env['account.move.line']._reconcile_plan(amls_grouped_together)
return all_reconciled_amls
def auto_reconcile(self):
""" Automatically reconcile amls given wizard's parameters.
:return: an action that opens all reconciled items and related amls (exchange diff, etc)
"""
self.ensure_one()
if self.search_mode == 'zero_balance':
reconciled_amls = self._auto_reconcile_zero_balance()
else:
# search_mode == 'one_to_one'
reconciled_amls = self._auto_reconcile_one_to_one()
reconciled_amls_and_related = self.env['account.move.line'].search([
('full_reconcile_id', 'in', reconciled_amls.full_reconcile_id.ids)
])
if reconciled_amls_and_related:
return {
'name': _("Automatically Reconciled Entries"),
'type': 'ir.actions.act_window',
'res_model': 'account.move.line',
'context': "{'search_default_group_by_matching': True}",
'view_mode': 'list',
'domain': [('id', 'in', reconciled_amls_and_related.ids)],
}
else:
raise UserError(self.env._("Nothing to reconcile."))

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="view_account_auto_reconcile_wizard" model="ir.ui.view">
<field name="name">account.auto.reconcile.wizard.form</field>
<field name="model">account.auto.reconcile.wizard</field>
<field name="arch" type="xml">
<form string="Reconcile automatically">
<field name="company_id" invisible="1"/>
<field name="line_ids" invisible="1"/>
<group>
<field name="search_mode" widget="radio" options="{'horizontal': true}"/>
<field name="account_ids" widget="many2many_tags" options="{'no_create': True, 'no_edit':True}"/>
<field name="partner_ids" widget="many2many_tags" options="{'no_create': True, 'no_edit':True}" invisible="not account_ids"/>
<field name="from_date" invisible="search_mode == 'zero_balance'"/>
<field name="to_date"/>
</group>
<footer>
<button string="Reconcile" class="btn-primary" name="auto_reconcile" type="object" data-hotkey="v"/>
<button special="cancel" data-hotkey="z"/>
</footer>
</form>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,426 @@
from odoo import api, models, fields, _
from odoo.exceptions import UserError
from odoo.fields import Domain
from odoo.tools import date_utils
from odoo.addons.account.models.company import SOFT_LOCK_DATE_FIELDS, LOCK_DATE_FIELDS
from datetime import date, timedelta
class AccountChangeLockDate(models.TransientModel):
"""
This wizard is used to change the lock date
"""
_name = 'account.change.lock.date'
_description = 'Change Lock Date'
company_id = fields.Many2one(
comodel_name='res.company',
required=True,
readonly=True,
default=lambda self: self.env.company,
)
fiscalyear_lock_date = fields.Date(
string='Lock Everything',
default=lambda self: self.env.company.fiscalyear_lock_date,
help="Any entry up to and including that date will be postponed to a later time, in accordance with its journal's sequence.",
)
fiscalyear_lock_date_for_me = fields.Date(
string='Lock Everything For Me',
compute='_compute_lock_date_exceptions',
)
fiscalyear_lock_date_for_everyone = fields.Date(
string='Lock Everything For Everyone',
compute='_compute_lock_date_exceptions',
)
min_fiscalyear_lock_date_exception_for_me_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
min_fiscalyear_lock_date_exception_for_everyone_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
tax_lock_date = fields.Date(
string="Lock Tax Return",
default=lambda self: self.env.company.tax_lock_date,
help="Any entry with taxes up to and including that date will be postponed to a later time, in accordance with its journal's sequence. "
"The tax lock date is automatically set when the tax closing entry is posted.",
)
tax_lock_date_for_me = fields.Date(
string='Lock Tax Return For Me',
compute='_compute_lock_date_exceptions',
)
tax_lock_date_for_everyone = fields.Date(
string='Lock Tax Return For Everyone',
compute='_compute_lock_date_exceptions',
)
min_tax_lock_date_exception_for_me_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
min_tax_lock_date_exception_for_everyone_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
sale_lock_date = fields.Date(
string='Lock Sales',
default=lambda self: self.env.company.sale_lock_date,
help="Any sales entry prior to and including this date will be postponed to a later date, in accordance with its journal's sequence.",
)
sale_lock_date_for_me = fields.Date(
string='Lock Sales For Me',
compute='_compute_lock_date_exceptions',
)
sale_lock_date_for_everyone = fields.Date(
string='Lock Sales For Everyone',
compute='_compute_lock_date_exceptions',
)
min_sale_lock_date_exception_for_me_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
min_sale_lock_date_exception_for_everyone_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
purchase_lock_date = fields.Date(
string='Lock Purchases',
default=lambda self: self.env.company.purchase_lock_date,
help="Any purchase entry prior to and including this date will be postponed to a later date, in accordance with its journal's sequence.",
)
purchase_lock_date_for_me = fields.Date(
string='Lock Purchases For Me',
compute='_compute_lock_date_exceptions',
)
purchase_lock_date_for_everyone = fields.Date(
string='Lock Purchases For Everyone',
compute='_compute_lock_date_exceptions',
)
min_purchase_lock_date_exception_for_me_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
min_purchase_lock_date_exception_for_everyone_id = fields.Many2one(
comodel_name='account.lock_exception',
compute='_compute_lock_date_exceptions',
)
hard_lock_date = fields.Date(
string='Hard Lock',
default=lambda self: self.env.company.hard_lock_date,
help="Any entry up to and including that date will be postponed to a later time, in accordance with its journal sequence. "
"This lock date is irreversible and does not allow any exception.",
)
current_hard_lock_date = fields.Date(
string='Current Hard Lock',
related='company_id.hard_lock_date',
readonly=True,
)
exception_needed_fields = fields.Char(
# String of comma separated values of the field(s) the exception applies to
compute='_compute_exception_needed_fields',
)
exception_applies_to = fields.Selection(
string='Exception applies',
selection=[
('me', "for me"),
('everyone', "for everyone"),
],
default='me',
required=True,
)
exception_duration = fields.Selection(
string='Exception Duration',
selection=[
('5min', "for 5 minutes"),
('15min', "for 15 minutes"),
('1h', "for 1 hour"),
('24h', "for 24 hours"),
('forever', "forever"),
],
default='5min',
required=True,
)
exception_reason = fields.Char(
string='Exception Reason',
)
show_draft_entries_warning = fields.Boolean(
string="Show Draft Entries Warning",
compute='_compute_show_draft_entries_warning',
)
show_posted_tax_closing_warning = fields.Boolean(compute='_compute_show_posted_tax_closing_warning')
@api.depends('company_id')
@api.depends_context('user', 'company')
def _compute_lock_date_exceptions(self):
for wizard in self:
exceptions = self.env['account.lock_exception'].search(
self.env['account.lock_exception']._get_active_exceptions_domain(wizard.company_id, SOFT_LOCK_DATE_FIELDS)
)
for field in SOFT_LOCK_DATE_FIELDS:
field_exceptions = exceptions.filtered(lambda e: e.lock_date_field == field)
field_exceptions_for_me = field_exceptions.filtered(lambda e: e.user_id.id == self.env.user.id)
field_exceptions_for_everyone = field_exceptions.filtered(lambda e: not e.user_id.id)
min_exception_for_me = min(field_exceptions_for_me, key=lambda e: e[field] or date.min) if field_exceptions_for_me else False
min_exception_for_everyone = min(field_exceptions_for_everyone, key=lambda e: e[field] or date.min) if field_exceptions_for_everyone else False
wizard[f"min_{field}_exception_for_me_id"] = min_exception_for_me
wizard[f"min_{field}_exception_for_everyone_id"] = min_exception_for_everyone
wizard[f"{field}_for_me"] = min_exception_for_me.lock_date if min_exception_for_me else False
wizard[f"{field}_for_everyone"] = min_exception_for_everyone.lock_date if min_exception_for_everyone else False
def _get_draft_moves_in_locked_period_domain(self):
self.ensure_one()
lock_date_domains = []
if self.hard_lock_date:
lock_date_domains.append([('date', '<=', self.hard_lock_date)])
if self.fiscalyear_lock_date:
lock_date_domains.append([('date', '<=', self.fiscalyear_lock_date)])
if self.sale_lock_date:
lock_date_domains.append([
('date', '<=', self.sale_lock_date),
('journal_id.type', '=', 'sale')])
if self.purchase_lock_date:
lock_date_domains.append([
('date', '<=', self.purchase_lock_date),
('journal_id.type', '=', 'purchase')])
return (
Domain('company_id', 'child_of', self.env.company.id)
& Domain('state', '=', 'draft')
& Domain.OR(lock_date_domains)
)
@api.depends('fiscalyear_lock_date', 'tax_lock_date', 'sale_lock_date', 'purchase_lock_date', 'hard_lock_date')
def _compute_show_draft_entries_warning(self):
for wizard in self:
draft_entries = self.env['account.move'].search(self._get_draft_moves_in_locked_period_domain(), limit=1)
wizard.show_draft_entries_warning = bool(draft_entries)
def _get_posted_tax_closings_in_locked_period_domain(self):
self.ensure_one()
return [
('date', '>', self.tax_lock_date),
('closing_return_id.type_id.report_id.root_report_id', '=', self.env.ref('account.generic_tax_report').id),
('state', '=', 'posted'),
]
@api.depends('tax_lock_date')
def _compute_show_posted_tax_closing_warning(self):
for wizard in self:
wizard.show_posted_tax_closing_warning = bool(self.env['account.move'].search(wizard._get_posted_tax_closings_in_locked_period_domain(), limit=1))
def _get_changes_needing_exception(self):
self.ensure_one()
return {
field: self[field]
for field in SOFT_LOCK_DATE_FIELDS
if self.env.company[field] and (not self[field] or self[field] < self.env.company[field])
}
@api.depends(*SOFT_LOCK_DATE_FIELDS)
def _compute_exception_needed_fields(self):
for wizard in self:
changes_needing_exception = wizard._get_changes_needing_exception()
wizard.exception_needed_fields = ','.join(changes_needing_exception)
def _prepare_lock_date_values(self, exception_vals_list=None):
"""
Return a dictionary (lock date field -> field value)
It only contains lock dates which are changed and for which no exception is added
"""
self.ensure_one()
if self.env.company.hard_lock_date and (not self.hard_lock_date or self.hard_lock_date < self.env.company.hard_lock_date):
raise UserError(_('It is not possible to decrease or remove the Hard Lock Date.'))
lock_date_values = {
field: self[field]
for field in LOCK_DATE_FIELDS
if self[field] != self.env.company[field]
}
for lock_date in lock_date_values.values():
if lock_date and lock_date > fields.Date.context_today(self):
raise UserError(_('You cannot set a Lock Date in the future.'))
# We do not change fields for which we add an exception
if exception_vals_list:
for exception_vals in exception_vals_list:
for field in LOCK_DATE_FIELDS:
if field in exception_vals:
lock_date_values.pop(field, None)
return lock_date_values
def _prepare_exception_values(self):
self.ensure_one()
changes_needing_exception = self._get_changes_needing_exception()
if not changes_needing_exception:
return False
# Exceptions for everyone and forever are just "normal" changes to the lock date.
if self.exception_applies_to == 'everyone' and self.exception_duration == 'forever':
return False
exception_errors = []
if not self.exception_applies_to:
exception_errors.append(_('You need to select who the exception applies to.'))
if not self.exception_duration:
exception_errors.append(_('You need to select a duration for the exception.'))
if exception_errors:
raise UserError('\n'.join(exception_errors))
exception_base_values = {
'company_id': self.env.company.id,
}
exception_base_values['user_id'] = {
'me': self.env.user.id,
'everyone': False,
}[self.exception_applies_to]
exception_timedelta = {
'5min': timedelta(minutes=5),
'15min': timedelta(minutes=15),
'1h': timedelta(hours=1),
'24h': timedelta(hours=24),
'forever': False,
}[self.exception_duration]
if exception_timedelta:
exception_base_values['end_datetime'] = self.env.cr.now() + exception_timedelta
if self.exception_reason:
exception_base_values['reason'] = self.exception_reason
exception_vals_list = [
{
**exception_base_values,
field: value,
}
for field, value in changes_needing_exception.items()
]
return exception_vals_list
def _get_current_period_dates(self, lock_date_field):
""" Gets the date_from - either the previous lock date or the start of the fiscal year.
"""
self.ensure_one()
company_lock_date = self.env.company[lock_date_field]
if company_lock_date:
date_from = company_lock_date + timedelta(days=1)
else:
date_from = date_utils.get_fiscal_year(self[lock_date_field])[0]
return date_from, self[lock_date_field]
def _create_default_report_external_values(self, lock_date_field):
# to be overriden
pass
def _change_lock_date(self, lock_date_values=None):
self.ensure_one()
if lock_date_values is None:
lock_date_values = self._prepare_lock_date_values()
tax_lock_date = lock_date_values.get('tax_lock_date', None)
if tax_lock_date and tax_lock_date != self.env.company['tax_lock_date']:
self._create_default_report_external_values('tax_lock_date')
fiscalyear_lock_date = lock_date_values.get('fiscalyear_lock_date', None)
hard_lock_date = lock_date_values.get('hard_lock_date', None)
if fiscalyear_lock_date or hard_lock_date:
fiscal_lock_date, field = max([
(fiscalyear_lock_date, 'fiscalyear_lock_date'),
(hard_lock_date, 'hard_lock_date'),
], key=lambda t: t[0] or date.min)
company_fiscal_lock_date = max(
self.env.company.fiscalyear_lock_date or date.min,
self.env.company.hard_lock_date or date.min,
)
if fiscal_lock_date != company_fiscal_lock_date:
self._create_default_report_external_values(field)
self.env.company.sudo().write(lock_date_values)
def change_lock_date(self):
self.ensure_one()
if self.env.user.has_group('account.group_account_manager'):
exception_vals_list = self._prepare_exception_values()
changed_lock_date_values = self._prepare_lock_date_values(exception_vals_list=exception_vals_list)
if exception_vals_list:
self.env['account.lock_exception'].create(exception_vals_list)
self._change_lock_date(changed_lock_date_values)
else:
raise UserError(_('Only Billing Administrators are allowed to change lock dates!'))
return {'type': 'ir.actions.act_window_close'}
def action_show_draft_moves_in_locked_period(self):
self.ensure_one()
return {
'view_mode': 'list',
'name': _('Draft Entries'),
'res_model': 'account.move',
'type': 'ir.actions.act_window',
'domain': self._get_draft_moves_in_locked_period_domain(),
'search_view_id': [self.env.ref('account.view_account_move_filter').id, 'search'],
'views': [[self.env.ref('account.view_move_tree_multi_edit').id, 'list'], [self.env.ref('account.view_move_form').id, 'form']],
}
def action_show_posted_tax_closing_in_locked_period(self):
self.ensure_one()
posted_closings = self.env['account.move'].search(self._get_posted_tax_closings_in_locked_period_domain())
return self.env['account.return'].action_open_tax_return_view(additional_return_domain=[('id', 'in', posted_closings.closing_return_id.ids)])
def action_reopen_wizard(self):
# This action can be used to keep the wizard open after doing something else
return {
'type': 'ir.actions.act_window',
'res_model': self._name,
'res_id': self.id,
'view_mode': 'form',
'target': 'new',
}
def _action_revoke_min_exception(self, exception_field):
self.ensure_one()
exception = self[exception_field]
if exception:
exception.action_revoke()
self._compute_lock_date_exceptions()
return self.action_reopen_wizard()
def action_revoke_min_sale_lock_date_exception_for_me(self):
return self._action_revoke_min_exception('min_sale_lock_date_exception_for_me_id')
def action_revoke_min_purchase_lock_date_exception_for_me(self):
return self._action_revoke_min_exception('min_purchase_lock_date_exception_for_me_id')
def action_revoke_min_tax_lock_date_exception_for_me(self):
return self._action_revoke_min_exception('min_tax_lock_date_exception_for_me_id')
def action_revoke_min_fiscalyear_lock_date_exception_for_me(self):
return self._action_revoke_min_exception('min_fiscalyear_lock_date_exception_for_me_id')
def action_revoke_min_sale_lock_date_exception_for_everyone(self):
return self._action_revoke_min_exception('min_sale_lock_date_exception_for_everyone_id')
def action_revoke_min_purchase_lock_date_exception_for_everyone(self):
return self._action_revoke_min_exception('min_purchase_lock_date_exception_for_everyone_id')
def action_revoke_min_tax_lock_date_exception_for_everyone(self):
return self._action_revoke_min_exception('min_tax_lock_date_exception_for_everyone_id')
def action_revoke_min_fiscalyear_lock_date_exception_for_everyone(self):
return self._action_revoke_min_exception('min_fiscalyear_lock_date_exception_for_everyone_id')

View File

@@ -0,0 +1,248 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<data>
<record id="view_account_change_lock_date" model="ir.ui.view">
<field name="name">account.change.lock.date.form</field>
<field name="model">account.change.lock.date</field>
<field name="arch" type="xml">
<form>
<sheet>
<group>
<field name="show_draft_entries_warning" invisible="True"/>
<div class="alert alert-warning mb-0 d-flex gap-2 flex-wrap" role="alert"
colspan="2"
invisible="not show_draft_entries_warning">
There are still draft entries in the period you want to lock.
You should either post or delete them.
<a type="object"
class="oe_link fw-bold"
name="action_show_draft_moves_in_locked_period"
icon="east">
Review
</a>
</div>
<field name="show_posted_tax_closing_warning" invisible="True"/>
<div class="alert alert-warning mb-0 d-flex gap-2 flex-wrap" role="alert"
colspan="2"
invisible="not show_posted_tax_closing_warning">
A posted tax return closing entry exists after this tax lock date. You might want to reset the related tax return to non-submitted.
<a type="object"
class="oe_link fw-bold"
name="action_show_posted_tax_closing_in_locked_period"
icon="east">
Review
</a>
</div>
<div class="text-muted mb-1" colspan="2">
<i>Lock transactions up to specific dates, inclusive</i>
</div>
<field name="company_id" invisible="True"/>
<field name="min_sale_lock_date_exception_for_me_id" invisible="True"/>
<field name="min_purchase_lock_date_exception_for_me_id" invisible="True"/>
<field name="min_tax_lock_date_exception_for_me_id" invisible="True"/>
<field name="min_fiscalyear_lock_date_exception_for_me_id" invisible="True"/>
<field name="min_sale_lock_date_exception_for_everyone_id" invisible="True"/>
<field name="min_purchase_lock_date_exception_for_everyone_id" invisible="True"/>
<field name="min_tax_lock_date_exception_for_everyone_id" invisible="True"/>
<field name="min_fiscalyear_lock_date_exception_for_everyone_id" invisible="True"/>
<label for="sale_lock_date"/>
<div class="d-flex">
<field name="sale_lock_date" placeholder="Not locked"
class="oe_inline"
decoration-info="exception_needed_fields and 'sale_lock_date' in exception_needed_fields"
options="{'warning': 'future'}"/>
<span class="text-muted o_form_label"
invisible="not min_sale_lock_date_exception_for_me_id">
For me:
<field name="sale_lock_date_for_me" nolabel="1" class="oe_inline"
invisible="not sale_lock_date_for_me"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_sale_lock_date_exception_for_me">
Revoke
</a>
</span>
<span class="text-muted o_form_label"
invisible="not min_sale_lock_date_exception_for_me_id
or not min_sale_lock_date_exception_for_everyone_id">
<span style="white-space: pre">; </span>
</span>
<span class="text-muted o_form_label"
invisible="not min_sale_lock_date_exception_for_everyone_id">
For everyone:
<field name="sale_lock_date_for_everyone" nolabel="1" class="oe_inline"
invisible="not sale_lock_date_for_everyone"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_sale_lock_date_exception_for_everyone">
Revoke
</a>
</span>
</div>
<label for="purchase_lock_date"/>
<div class="d-flex">
<field name="purchase_lock_date" placeholder="Not locked"
class="oe_inline"
decoration-info="exception_needed_fields and 'purchase_lock_date' in exception_needed_fields"
options="{'warning': 'future'}"/>
<span class="text-muted o_form_label"
invisible="not min_purchase_lock_date_exception_for_me_id">
For me:
<field name="purchase_lock_date_for_me" nolabel="1" class="oe_inline"
invisible="not purchase_lock_date_for_me"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_purchase_lock_date_exception_for_me">
Revoke
</a>
</span>
<span class="text-muted o_form_label"
invisible="not min_purchase_lock_date_exception_for_me_id
or not min_purchase_lock_date_exception_for_everyone_id">
<span style="white-space: pre">; </span>
</span>
<span class="text-muted o_form_label"
invisible="not min_purchase_lock_date_exception_for_everyone_id">
For everyone:
<field name="purchase_lock_date_for_everyone" nolabel="1" class="oe_inline"
invisible="not purchase_lock_date_for_everyone"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_purchase_lock_date_exception_for_everyone">
Revoke
</a>
</span>
</div>
<label for="tax_lock_date"/>
<div class="d-flex">
<field name="tax_lock_date" placeholder="Not locked"
class="oe_inline"
decoration-info="exception_needed_fields and 'tax_lock_date' in exception_needed_fields"
options="{'warning': 'future'}"/>
<span class="text-muted"
invisible="min_tax_lock_date_exception_for_me_id or min_tax_lock_date_exception_for_everyone_id">
<i class="ms-2">after a tax closing</i>
</span>
<span class="text-muted o_form_label"
invisible="not min_tax_lock_date_exception_for_me_id">
For me:
<field name="tax_lock_date_for_me" nolabel="1" class="oe_inline"
invisible="not tax_lock_date_for_me"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_tax_lock_date_exception_for_me">
Revoke
</a>
</span>
<span class="text-muted o_form_label"
invisible="not min_tax_lock_date_exception_for_me_id
or not min_tax_lock_date_exception_for_everyone_id">
<span style="white-space: pre">; </span>
</span>
<span class="text-muted o_form_label"
invisible="not min_tax_lock_date_exception_for_everyone_id">
For everyone:
<field name="tax_lock_date_for_everyone" nolabel="1" class="oe_inline"
invisible="not tax_lock_date_for_everyone"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_tax_lock_date_exception_for_everyone">
Revoke
</a>
</span>
</div>
<label for="fiscalyear_lock_date"/>
<div class="d-flex">
<field name="fiscalyear_lock_date" placeholder="Not locked"
class="oe_inline"
decoration-info="exception_needed_fields and 'fiscalyear_lock_date' in exception_needed_fields"
options="{'warning': 'future'}"/>
<span class="text-muted"
invisible="min_fiscalyear_lock_date_exception_for_me_id or min_fiscalyear_lock_date_exception_for_everyone_id">
<i class="ms-2">but allow exceptions</i>
</span>
<span class="text-muted o_form_label"
invisible="not min_fiscalyear_lock_date_exception_for_me_id">
For me:
<field name="fiscalyear_lock_date_for_me" nolabel="1" class="oe_inline"
invisible="not fiscalyear_lock_date_for_me"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_fiscalyear_lock_date_exception_for_me">
Revoke
</a>
</span>
<span class="text-muted o_form_label"
invisible="not min_fiscalyear_lock_date_exception_for_me_id
or not min_fiscalyear_lock_date_exception_for_everyone_id">
<span style="white-space: pre">; </span>
</span>
<span class="text-muted o_form_label"
invisible="not min_fiscalyear_lock_date_exception_for_everyone_id">
For everyone:
<field name="fiscalyear_lock_date_for_everyone" nolabel="1" class="oe_inline"
invisible="not fiscalyear_lock_date_for_everyone"/>
<a type="object"
class="oe_link fw-bold"
name="action_revoke_min_fiscalyear_lock_date_exception_for_everyone">
Revoke
</a>
</span>
</div>
<div class="alert alert-info ps-3 mt-2 mb-0 d-flex flex-wrap" role="alert"
colspan="2"
style="white-space: pre;"
invisible="not exception_needed_fields">
<span>Exception</span>
<field name="exception_applies_to" class="oe_inline mx-3"/>
<field name="exception_duration" class="oe_inline"/>
<field name="exception_reason"
placeholder="Reason..."
class="oe_inline mx-3 flex-grow-1"
widget="text"
options="{'line_breaks': False}"
invisible="exception_applies_to == 'everyone' and exception_duration == 'forever'"/>
</div>
<div class="d-flex justify-content-start" colspan="2">
<div class="alert alert-danger ps-3 mb-3" role="alert">
<div>Need an irreversible lock to ensure inalterability, for all users?</div>
<div class="d-flex">
<label for="hard_lock_date"/>
<field name="hard_lock_date" placeholder="Not locked"
class="oe_inline mx-3"
decoration-info="exception_needed_fields and 'hard_lock_date' in exception_needed_fields"
options="{'warning': 'future'}"/>
<span class="text-danger o_form_label" invisible="hard_lock_date == current_hard_lock_date">
<i>This change is irreversible</i>
</span>
</div>
</div>
</div>
</group>
</sheet>
<footer>
<button string="Save" name="change_lock_date" type="object" class="btn-primary" data-hotkey="q"/>
<button class="btn-secondary" special="cancel" data-hotkey="x"/>
</footer>
</form>
</field>
</record>
<record id="action_view_account_change_lock_date" model="ir.actions.act_window">
<field name="name">Lock Journal Entries</field>
<field name="res_model">account.change.lock.date</field>
<field name="view_mode">form</field>
<field name="view_id" ref="view_account_change_lock_date"/>
<field name="target">new</field>
</record>
<menuitem
id="menu_action_change_lock_date"
name="Lock Dates…"
action="action_view_account_change_lock_date"
parent="account.account_closing_menu"
sequence="70"
groups="account.group_account_manager"/>
</data>
</odoo>

View File

@@ -0,0 +1,794 @@
from collections import defaultdict
from datetime import timedelta
from odoo import api, Command, fields, models, _
from odoo.exceptions import UserError
from odoo.tools import groupby, SQL
from odoo.tools.misc import formatLang
class AccountReconcileWizard(models.TransientModel):
""" This wizard is used to reconcile selected account.move.line. """
_name = 'account.reconcile.wizard'
_inherit = ['analytic.mixin']
_description = 'Account reconciliation wizard'
_check_company_auto = True
@api.model
def default_get(self, fields):
res = super().default_get(fields)
if 'move_line_ids' not in fields:
return res
if self.env.context.get('active_model') != 'account.move.line' or not self.env.context.get('active_ids'):
raise UserError(_('This can only be used on journal items'))
move_line_ids = self.env['account.move.line'].browse(self.env.context['active_ids'])
accounts = move_line_ids.account_id
if len(accounts) > 2:
raise UserError(_(
'You can only reconcile entries with up to two different accounts: %s',
', '.join(accounts.mapped('display_name')),
))
shadowed_aml_values = None
if len(accounts) == 2:
shadowed_aml_values = {
aml: {'account_id': move_line_ids[0].account_id}
for aml in move_line_ids.filtered(lambda line: line.account_id != move_line_ids[0].account_id)
}
move_line_ids._check_amls_exigibility_for_reconciliation(shadowed_aml_values=shadowed_aml_values)
res['move_line_ids'] = [Command.set(move_line_ids.ids)]
return res
company_id = fields.Many2one(comodel_name='res.company', required=True, readonly=True, compute='_compute_company_id')
move_line_ids = fields.Many2many(
comodel_name='account.move.line',
string='Move lines to reconcile',
required=True)
reco_account_id = fields.Many2one(
comodel_name='account.account',
string='Reconcile Account',
compute='_compute_reco_wizard_data')
amount = fields.Monetary(
string='Amount in company currency',
currency_field='company_currency_id',
compute='_compute_reco_wizard_data')
company_currency_id = fields.Many2one(comodel_name='res.currency', string='Company currency', related='company_id.currency_id')
amount_currency = fields.Monetary(
string='Amount',
currency_field='reco_currency_id',
compute='_compute_reco_wizard_data')
reco_currency_id = fields.Many2one(
comodel_name='res.currency',
string='Currency to use for reconciliation',
compute='_compute_reco_wizard_data')
edit_mode_amount = fields.Monetary(
currency_field='company_currency_id',
compute='_compute_edit_mode_amount',
)
edit_mode_amount_currency = fields.Monetary(
string='Edit mode amount',
currency_field='edit_mode_reco_currency_id',
compute='_compute_edit_mode_amount_currency',
store=True,
readonly=False,
)
edit_mode_reco_currency_id = fields.Many2one(
comodel_name='res.currency',
compute='_compute_edit_mode_reco_currency',
)
edit_mode = fields.Boolean(
compute='_compute_edit_mode',
)
single_currency_mode = fields.Boolean(compute='_compute_single_currency_mode')
allow_partials = fields.Boolean(string="Allow partials", compute='_compute_allow_partials', store=True, readonly=False)
force_partials = fields.Boolean(compute='_compute_reco_wizard_data')
display_allow_partials = fields.Boolean(compute='_compute_display_allow_partials')
date = fields.Date(string='Date', compute='_compute_date', store=True, readonly=False)
journal_id = fields.Many2one(
comodel_name='account.journal',
string='Journal',
check_company=True,
domain="[('type', '=', 'general')]",
compute='_compute_journal_id',
store=True,
readonly=False,
required=True,
precompute=True)
account_id = fields.Many2one(
comodel_name='account.account',
string='Account',
check_company=True,
domain="[('account_type', '!=', 'off_balance')]")
is_rec_pay_account = fields.Boolean(compute='_compute_is_rec_pay_account')
to_partner_id = fields.Many2one(
comodel_name='res.partner',
string='Partner',
check_company=True,
compute='_compute_to_partner_id',
store=True,
readonly=False,
)
label = fields.Char(string='Label', default='Write-Off')
tax_id = fields.Many2one(
comodel_name='account.tax',
string='Tax',
default=False,
check_company=True)
to_check = fields.Boolean(
string='To Check',
default=False,
help='Check if you are not certain of all the information of the counterpart.')
is_write_off_required = fields.Boolean(
string='Is a write-off move required to reconcile',
compute='_compute_is_write_off_required')
is_transfer_required = fields.Boolean(
string='Is an account transfer required',
compute='_compute_reco_wizard_data')
transfer_warning_message = fields.Char(
string='Is an account transfer required to reconcile',
compute='_compute_reco_wizard_data')
transfer_from_account_id = fields.Many2one(
comodel_name='account.account',
string='Account Transfer From',
compute='_compute_reco_wizard_data')
lock_date_violated_warning_message = fields.Char(
string='Is the date violating the lock date of moves',
compute='_compute_lock_date_violated_warning_message')
reco_model_id = fields.Many2one(
comodel_name='account.reconcile.model',
string='Reconciliation model',
store=False,
check_company=True)
reco_model_autocomplete_ids = fields.Many2many(
comodel_name='account.reconcile.model',
string='All reconciliation models',
compute='_compute_reco_model_autocomplete_ids')
# ==== Compute methods ====
@api.depends('move_line_ids.company_id')
def _compute_company_id(self):
for wizard in self:
wizard.company_id = wizard.move_line_ids[0].company_id
@api.depends('move_line_ids')
def _compute_single_currency_mode(self):
for wizard in self:
wizard.single_currency_mode = len(wizard.move_line_ids.currency_id - wizard.company_currency_id) <= 1
@api.depends('force_partials')
def _compute_allow_partials(self):
for wizard in self:
wizard.allow_partials = wizard.display_allow_partials and wizard.force_partials
@api.depends('move_line_ids')
def _compute_display_allow_partials(self):
""" We only display the allow partial checkbox if there is both credit and debit lines involved. """
for wizard in self:
wizard.display_allow_partials = has_debit_line = has_credit_line = False
for aml in wizard.move_line_ids:
if aml.balance > 0.0 or aml.amount_currency > 0.0:
has_debit_line = True
elif aml.balance < 0.0 or aml.amount_currency < 0.0:
has_credit_line = True
if has_debit_line and has_credit_line:
wizard.display_allow_partials = True
break
@api.depends('move_line_ids', 'journal_id', 'tax_id')
def _compute_date(self):
for wizard in self:
highest_date = max(aml.date for aml in wizard.move_line_ids)
temp_move = self.env['account.move'].new({'journal_id': wizard.journal_id.id})
wizard.date = temp_move._get_accounting_date(highest_date, bool(wizard.tax_id))
@api.depends('company_id')
def _compute_journal_id(self):
for wizard in self:
wizard.journal_id = self.env['account.journal'].search([
*self.env['account.journal']._check_company_domain(wizard.company_id),
('type', '=', 'general')
], limit=1)
@api.depends('account_id')
def _compute_is_rec_pay_account(self):
for wizard in self:
wizard.is_rec_pay_account = wizard.account_id.account_type in ('asset_receivable', 'liability_payable')
@api.depends('is_rec_pay_account')
def _compute_to_partner_id(self):
for wizard in self:
if wizard.is_rec_pay_account:
partners = wizard.move_line_ids.partner_id
wizard.to_partner_id = partners if len(partners) == 1 else None
else:
wizard.to_partner_id = None
@api.depends('amount', 'amount_currency')
def _compute_is_write_off_required(self):
""" We need a write-off if the balance is not 0 and if we don't allow partial reconciliation."""
for wizard in self:
wizard.is_write_off_required = not wizard.company_currency_id.is_zero(wizard.amount) \
or (wizard.reco_currency_id and not wizard.reco_currency_id.is_zero(wizard.amount_currency))
@api.depends('move_line_ids')
def _compute_reco_wizard_data(self):
""" Compute various data needed for the reco wizard.
1. The currency to use for the reconciliation:
- if only one foreign currency is present in move lines we use it, unless the reco_account is not
payable nor receivable,
- if no foreign currency or more than 1 are used we use the company's default currency.
2. The account the reconciliation will happen on.
3. Transfer data.
4. Write-off amounts.
"""
def get_transfer_data(move_lines):
amounts_per_account = defaultdict(float)
for line in move_lines:
amounts_per_account[line.account_id] += line.amount_residual
if abs(amounts_per_account[accounts[0]]) < abs(amounts_per_account[accounts[1]]):
transfer_from_account, transfer_to_account = accounts[0], accounts[1]
else:
transfer_from_account, transfer_to_account = accounts[1], accounts[0]
amls_to_transfer = amls.filtered(lambda aml: aml.account_id == transfer_from_account)
transfer_foreign_curr = amls.currency_id - amls.company_currency_id
if len(transfer_foreign_curr) == 1:
transfer_currency = transfer_foreign_curr
transfer_amount_currency = sum(aml.amount_currency for aml in amls_to_transfer)
else:
transfer_currency = amls.company_currency_id
transfer_amount_currency = sum(aml.balance for aml in amls_to_transfer)
if transfer_amount_currency == 0.0 and transfer_currency != amls.company_currency_id:
# handle the transfer of exchange diff
transfer_currency = amls.company_currency_id
transfer_amount_currency = sum(aml.balance for aml in amls_to_transfer)
amount_formatted = formatLang(self.env, abs(transfer_amount_currency), currency_obj=transfer_currency)
transfer_warning_message = _(
'An entry will transfer %(amount)s from %(from_account)s to %(to_account)s.',
amount=amount_formatted,
from_account=transfer_from_account.display_name if transfer_amount_currency < 0 else transfer_to_account.display_name,
to_account=transfer_to_account.display_name if transfer_amount_currency < 0 else transfer_from_account.display_name,
)
return {
'transfer_from_account_id': transfer_from_account,
'reco_account_id': transfer_to_account,
'transfer_warning_message': transfer_warning_message,
}
def get_reco_currency(amls, aml_values_map):
company_currency = amls.company_currency_id
foreign_currencies = amls.currency_id - company_currency
if len(foreign_currencies) == 0 or not all(amls.account_id.mapped('reconcile')):
return company_currency
elif len(foreign_currencies) == 1:
return foreign_currencies
else:
lines_with_residuals = self.env['account.move.line']
for residual, residual_values in aml_values_map.items():
if residual_values['amount_residual'] or residual_values['amount_residual_currency']:
lines_with_residuals += residual
if lines_with_residuals and len(lines_with_residuals.currency_id - company_currency) > 1:
# there is more than one residual and more than one currency in them
return False
return (lines_with_residuals.currency_id - company_currency) or company_currency
for wizard in self:
amls = wizard.move_line_ids._origin
accounts = amls.account_id # there is only 1 or 2 possible accounts
wizard.reco_currency_id = False
wizard.amount_currency = wizard.amount = 0.0
wizard.force_partials = True
wizard.transfer_from_account_id = wizard.transfer_warning_message = False
wizard.is_transfer_required = len(accounts) == 2
if wizard.is_transfer_required:
wizard.update(get_transfer_data(amls))
else:
wizard.reco_account_id = accounts
# Compute the residual amounts for each account.
shadowed_aml_values = {
aml: {'account_id': wizard.reco_account_id}
for aml in amls
}
# Batch the amls all together to know what should be reconciled and when.
plan_list, all_amls = amls._optimize_reconciliation_plan([amls], shadowed_aml_values=shadowed_aml_values)
# Prefetch data
all_amls.move_id
all_amls.matched_debit_ids
all_amls.matched_credit_ids
# All residual amounts are collected and updated until the creation of partials in batch.
# This is done that way to minimize the orm time for fields invalidation/mark as recompute and
# re-computation.
aml_values_map = {
aml: {
'aml': aml,
'amount_residual': aml.amount_residual,
'amount_residual_currency': aml.amount_residual_currency,
}
for aml in all_amls
}
plan = plan_list[0]
# residuals are subtracted from aml_values_map
# Same context as in reconcile()
amls.with_context(
no_exchange_difference=not all(accounts.mapped('reconcile')),
)._prepare_reconciliation_plan(plan, aml_values_map, shadowed_aml_values=shadowed_aml_values)
reco_currency = get_reco_currency(amls, aml_values_map)
if not reco_currency:
continue # stop the computation, no possible write-off => force partials
residual_amounts = {
aml: aml._prepare_move_line_residual_amounts(aml_values, reco_currency, shadowed_aml_values=shadowed_aml_values)
for aml, aml_values in aml_values_map.items()
}
if all(reco_currency in residual_values for residual_values in residual_amounts.values() if residual_values):
wizard.reco_currency_id = reco_currency
elif all(amls.company_currency_id in residual_values for residual_values in residual_amounts.values() if residual_values):
wizard.reco_currency_id = amls.company_currency_id
reco_currency = wizard.reco_currency_id
else:
continue # stop the computation, no possible write-off => force partials
# Compute write-off amounts
most_recent_line = max(amls, key=lambda aml: aml.date)
if not most_recent_line.amount_currency:
rate = rate_lower_bound = rate_upper_bound = 0.0
elif most_recent_line.currency_id == reco_currency:
rate = abs(most_recent_line.balance / most_recent_line.amount_currency)
# By estimating the rate from the most recent line, we are exposing ourselves to an estimation error because
# balance is amount_currency * rate, rounded to the nearest precision of the company currency. We now compute
# the lower/upper bounds of the estimated rate in order to determine which other AMLs share the same rate.
# For AMLs that share the same rate, we will use the existing amount_residual instead of recomputing it
# based on the amount_residual_currency and the rate.
rate_tolerance = amls.company_currency_id.rounding / 2 / abs(most_recent_line.amount_currency)
rate_lower_bound = rate - rate_tolerance
rate_upper_bound = rate + rate_tolerance
else:
rate = self.env['res.currency']._get_conversion_rate(reco_currency, amls.company_currency_id, most_recent_line.company_id, most_recent_line.date)
rate_lower_bound = rate_upper_bound = rate
# If an AML's rate is close enough to the reconciliation rate that it could be the same,
# use the `amount_residual` instead of computing `amount_residual_currency / rate` and rounding.
# We do this for the case where a single rate is used for all reconciled AMLs so we want to avoid
# creating an exchange diff because that would be weird.
amls_where_amounts_at_correct_rate = {
aml
for aml, residual_values in residual_amounts.items()
if (
aml.currency_id == reco_currency
and abs(aml.balance) >= aml.company_currency_id.round(abs(aml.amount_currency) * rate_lower_bound)
and abs(aml.balance) <= aml.company_currency_id.round(abs(aml.amount_currency) * rate_upper_bound)
)
}
wizard.amount_currency = sum(
residual_values[wizard.reco_currency_id]['residual']
for residual_values in residual_amounts.values()
if residual_values
)
amount_raw = sum(
(
residual_values[amls.company_currency_id]['residual']
if aml in amls_where_amounts_at_correct_rate and amls.company_currency_id in residual_values else
residual_values[wizard.reco_currency_id]['residual'] * rate
)
for aml, residual_values in residual_amounts.items()
if residual_values
)
wizard.amount = amls.company_currency_id.round(amount_raw)
wizard.force_partials = False
@api.depends('move_line_ids')
def _compute_edit_mode_amount_currency(self):
for wizard in self:
if wizard.edit_mode:
wizard.edit_mode_amount_currency = wizard.amount_currency
else:
wizard.edit_mode_amount_currency = 0.0
@api.depends('edit_mode_amount_currency')
def _compute_edit_mode_amount(self):
for wizard in self:
if wizard.edit_mode:
single_line = wizard.move_line_ids
rate = abs(single_line.amount_currency / single_line.balance) if single_line.balance else 0.0
wizard.edit_mode_amount = single_line.company_currency_id.round(wizard.edit_mode_amount_currency / rate) if rate else 0.0
else:
wizard.edit_mode_amount = 0.0
@api.depends('move_line_ids')
def _compute_edit_mode_reco_currency(self):
for wizard in self:
if wizard.edit_mode:
wizard.edit_mode_reco_currency_id = wizard.move_line_ids.currency_id
else:
wizard.edit_mode_reco_currency_id = False
@api.depends('move_line_ids')
def _compute_edit_mode(self):
for wizard in self:
wizard.edit_mode = len(wizard.move_line_ids) == 1
@api.depends('move_line_ids.move_id', 'date')
def _compute_lock_date_violated_warning_message(self):
for wizard in self:
date_after_lock = wizard._get_date_after_lock_date()
lock_date_violated_warning_message = None
if date_after_lock:
lock_date_violated_warning_message = _(
'The date you set violates the lock date of one of your entry. It will be overriden by the following date : %(replacement_date)s',
replacement_date=date_after_lock,
)
wizard.lock_date_violated_warning_message = lock_date_violated_warning_message
@api.depends('company_id', 'move_line_ids.partner_id', 'amount')
def _compute_reco_model_autocomplete_ids(self):
""" Computes available reconcile models, we only take manually created models that
have one (and only one) line, and have partners, amount, or journal that match the
ones of the entries.
"""
for wizard in self:
domain = [
('company_id', '=', wizard.company_id.id),
'|',
('match_partner_ids', '=', False),
('match_partner_ids', 'any', [('id', 'in', wizard.move_line_ids.partner_id.ids)]),
'|',
('match_amount', '=', False),
'|',
'&',
('match_amount', '=', 'lower'),
('match_amount_max', '>', wizard.amount),
'|',
'&',
('match_amount', '=', 'greater'),
('match_amount_min', '<', wizard.amount),
'&',
('match_amount', '=', 'between'),
'&',
('match_amount_min', '<', wizard.amount),
('match_amount_max', '>', wizard.amount),
'|',
('match_journal_ids', '=', False),
('match_journal_ids', 'in', wizard.move_line_ids.journal_id.ids),
('created_automatically', '=', False),
]
query = self.env['account.reconcile.model']._search(domain, bypass_access=True)
reco_model_ids = [r[0] for r in self.env.execute_query(SQL("""
SELECT account_reconcile_model.id
FROM %s
JOIN account_reconcile_model_line line ON line.model_id = account_reconcile_model.id
WHERE %s
GROUP BY account_reconcile_model.id
HAVING COUNT(account_reconcile_model.id) = 1
""", query.from_clause, query.where_clause or SQL("TRUE")))]
wizard.reco_model_autocomplete_ids = self.env['account.reconcile.model'].browse(reco_model_ids)
# ==== Onchange methods ====
@api.onchange('reco_model_id')
def _onchange_reco_model_id(self):
""" We prefill the write-off data with the reconcile model selected. """
if self.reco_model_id:
self.label = self.reco_model_id.line_ids.label
self.tax_id = self.reco_model_id.line_ids.tax_ids[0] if self.reco_model_id.line_ids[0].tax_ids else None
self.account_id = self.reco_model_id.line_ids.account_id
# ==== Python constrains ====
@api.constrains('edit_mode_amount_currency')
def _check_min_max_edit_mode_amount_currency(self):
for wizard in self:
if wizard.edit_mode:
if wizard.edit_mode_amount_currency == 0.0:
raise UserError(_('The amount of the write-off of a single line cannot be 0.'))
is_debit_line = wizard.move_line_ids.balance > 0.0 or wizard.move_line_ids.amount_currency > 0.0
if is_debit_line and wizard.edit_mode_amount_currency < 0.0:
raise UserError(_('The amount of the write-off of a single debit line should be strictly positive.'))
elif not is_debit_line and wizard.edit_mode_amount_currency > 0.0:
raise UserError(_('The amount of the write-off of a single credit line should be strictly negative.'))
# ==== Actions methods ====
def _action_open_wizard(self):
self.ensure_one()
return {
'name': _('Write-Off Entry'),
'type': 'ir.actions.act_window',
'view_type': 'form',
'view_mode': 'form',
'res_model': 'account.reconcile.wizard',
'target': 'new',
}
# ==== Business methods ====
def _get_date_after_lock_date(self):
self.ensure_one()
lock_dates = self.company_id._get_violated_lock_dates(self.date, bool(self.tax_id), self.journal_id)
if lock_dates:
return lock_dates[-1][0] + timedelta(days=1)
def _compute_write_off_taxes_data(self, partner):
""" Computes the data needed to fill the write-off lines related to taxes.
:return: a dict of the form {
'base_amount': 100.0,
'base_amount_currency': 200.0,
'tax_lines_data': [{
'tax_amount': 21.0,
'tax_amount_currency': 42.0,
'tax_tag_ids': [tax_tags],
'tax_account_id': id_of_account,
} * nr of repartition lines of the self.tax_id ],
}
"""
AccountTax = self.env['account.tax']
amount_currency = self.edit_mode_amount_currency or self.amount_currency
amount = self.edit_mode_amount or self.amount
rate = abs(amount_currency / amount)
tax_type = self.tax_id.type_tax_use if self.tax_id else None
is_refund = (tax_type == 'sale' and amount_currency > 0.0) or (tax_type == 'purchase' and amount_currency < 0.0)
base_line = AccountTax._prepare_base_line_for_taxes_computation(
self,
partner_id=partner,
currency_id=self.reco_currency_id,
tax_ids=self.tax_id,
price_unit=amount_currency,
quantity=1.0,
account_id=self.account_id,
is_refund=is_refund,
rate=rate,
special_mode='total_included',
)
base_lines = [base_line]
AccountTax._add_tax_details_in_base_lines(base_lines, self.company_id)
AccountTax._round_base_lines_tax_details(base_lines, self.company_id)
AccountTax._add_accounting_data_in_base_lines_tax_details(base_lines, self.company_id, include_caba_tags=True)
tax_results = AccountTax._prepare_tax_lines(base_lines, self.company_id)
_base_line, base_to_update = tax_results['base_lines_to_update'][0] # we can only have one baseline
tax_lines_data = []
for tax_line_vals in tax_results['tax_lines_to_add']:
tax_lines_data.append({
'tax_amount': tax_line_vals['balance'],
'tax_amount_currency': tax_line_vals['amount_currency'],
'tax_tag_ids': tax_line_vals['tax_tag_ids'],
'tax_account_id': tax_line_vals['account_id'],
})
base_amount_currency = base_to_update['amount_currency']
base_amount = amount - sum(entry['tax_amount'] for entry in tax_lines_data)
return {
'base_amount': base_amount,
'base_amount_currency': base_amount_currency,
'base_tax_tag_ids': base_to_update['tax_tag_ids'],
'tax_lines_data': tax_lines_data,
}
def _create_write_off_lines(self, partner=None):
if not partner:
partner = self.env['res.partner']
to_partner = self.to_partner_id if self.is_rec_pay_account else partner
tax_data = self._compute_write_off_taxes_data(to_partner) if self.tax_id else None
amount_currency = self.edit_mode_amount_currency or self.amount_currency
amount = self.edit_mode_amount or self.amount
line_ids_commands = [
Command.create({
'name': self.label or _('Write-Off'),
'account_id': self.reco_account_id.id,
'partner_id': partner.id,
'currency_id': self.reco_currency_id.id,
'amount_currency': -amount_currency,
'balance': -amount,
}),
Command.create({
'name': self.label,
'account_id': self.account_id.id,
'partner_id': to_partner.id,
'currency_id': self.reco_currency_id.id,
'analytic_distribution': self.analytic_distribution,
'tax_ids': self.tax_id.ids,
'tax_tag_ids': None if not tax_data else tax_data['base_tax_tag_ids'],
'amount_currency': amount_currency if not tax_data else tax_data['base_amount_currency'],
'balance': amount if not tax_data else tax_data['base_amount'],
}),
]
# Add taxes lines to the write-off lines, one per repartition line
if tax_data:
for tax_datum in tax_data['tax_lines_data']:
line_ids_commands.append(Command.create({
'name': self.tax_id.name,
'account_id': tax_datum['tax_account_id'],
'partner_id': to_partner.id,
'currency_id': self.reco_currency_id.id,
'tax_tag_ids': tax_datum['tax_tag_ids'],
'amount_currency': tax_datum['tax_amount_currency'],
'balance': tax_datum['tax_amount'],
}))
return line_ids_commands
def create_write_off(self):
""" Create write-off move lines with the data provided in the wizard. """
self.ensure_one()
partners = self.move_line_ids.partner_id
partner = partners if len(partners) == 1 else None
write_off_vals = {
'journal_id': self.journal_id.id,
'company_id': self.company_id.id,
'date': self._get_date_after_lock_date() or self.date,
'move_type': 'entry',
'review_state': 'todo' if self.to_check else 'reviewed',
'line_ids': self._create_write_off_lines(partner=partner)
}
write_off_move = self.env['account.move'].with_context(
skip_invoice_sync=True,
skip_invoice_line_sync=True,
).create(write_off_vals)
write_off_move.action_post()
return write_off_move.with_env(self.env)
def create_transfer(self):
""" Create transfer move.
We transfer lines squashed by partner and by currency to keep the partner ledger correct.
By default, the source line and the destination line of each transfer are linked to the same partner.
However, it can happen that the moves that are being reconciled together come from different partners
(e.g. reconciling an invoice of Partner X with a bill of Parnter Y).
In that case, one of the transfer lines should be set to the other partner.
Otherwise, the partner ledger will be wrong for both users.
"""
self.ensure_one()
line_ids = []
lines_to_transfer = self.move_line_ids.filtered(lambda line: line.account_id == self.transfer_from_account_id)
# The lines that are not transferred will be used to determine the partners of the destination lines
other_lines = self.move_line_ids.filtered(lambda line: line.account_id == self.reco_account_id)
# Default dict for the destination lines. It contains the inverse of the source lines
# {(partner, currency, sign): {'balance': float, 'amount_currency': float}}
default_destination_data = dict()
# Dict generated from the lines linked to the reconcile model.
# It is splitted by partner and represents the possible partners and the amount max that can be used
# for the destination lines.
# {(currency, sign): {(partner): {'balance': float, 'amount_currency': float}}}
amounts_by_partner = defaultdict(lambda: defaultdict(lambda: defaultdict(float)))
# Final dict containing the data from which the destination lines will be created
# {(partner, currency, sign): {'balance': float, 'amount_currency': float}}
destination_data = defaultdict(lambda: defaultdict(float))
for (partner, currency), lines_to_transfer_partner in groupby(lines_to_transfer, lambda l: (l.partner_id, l.currency_id)):
amount = sum(line.amount_residual for line in lines_to_transfer_partner)
amount_currency = sum(line.amount_residual_currency for line in lines_to_transfer_partner)
line_ids += [
Command.create({
'name': _('Transfer to %s', self.reco_account_id.display_name),
'account_id': self.transfer_from_account_id.id,
'partner_id': partner.id,
'currency_id': currency.id,
'amount_currency': -amount_currency,
'balance': -amount,
}),
]
sign = -1 if amount < 0 else 1
# By default, the partner of the destination line will be the same than the one of the source line.
# As the transfer move should be balanced, the amounts defined here represent the total amount that
# will be in the destination lines.
# They may be split between several partners though.
default_destination_data[partner, currency, sign] = {
'balance': amount,
'amount_currency': amount_currency,
}
# Run through the lines linked to the reconcile account to determine the possible partners and amounts for the destination
# lines of the transfer
for (partner, currency), lines_to_transfer_partner in groupby(other_lines, lambda l: (l.partner_id, l.currency_id)):
amount = -sum(line.amount_residual for line in lines_to_transfer_partner)
amount_currency = -sum(line.amount_residual_currency for line in lines_to_transfer_partner)
sign = -1 if amount < 0 else 1
# If the partner, currency and sign of the amounts match one of the default data, it is kept for the destination lines.
# The amounts will be adapted with the remaining amounts.
if (partner, currency, sign) in default_destination_data:
default_amount = default_destination_data[partner, currency, sign]['balance']
default_amount_currency = default_destination_data[partner, currency, sign]['amount_currency']
amount_to_transfer = min(abs(amount), abs(default_amount)) * sign
amount_currency_to_transfer = min(abs(amount_currency), abs(default_amount_currency)) * sign
destination_data[partner, currency, sign] = {
'balance': amount_to_transfer,
'amount_currency': amount_currency_to_transfer,
}
default_amount -= amount_to_transfer
default_amount_currency -= amount_currency_to_transfer
amount -= amount_to_transfer
amount_currency -= amount_currency_to_transfer
if not currency.is_zero(abs(default_amount)):
# Update the default amounts with the remaining amounts that have not been kept
default_destination_data[partner, currency, sign] = {
'balance': default_amount,
'amount_currency': default_amount_currency,
}
else:
# Delete the key if there is no remaining amount
del default_destination_data[partner, currency, sign]
if not currency.is_zero(abs(amount)):
amounts_by_partner[currency, sign][partner] = {
'balance': amount,
'amount_currency': amount_currency,
}
# Run through what's left of the default data and try to find a partner that matches the currency and sign.
# If none is found, the partner from the source line is used.
for (partner, currency, sign) in default_destination_data:
amount = default_destination_data[partner, currency, sign]['balance']
amount_currency = default_destination_data[partner, currency, sign]['amount_currency']
# Loop on all the partners with the same currency and sign
for p in amounts_by_partner[currency, sign]:
if amount == 0:
break
amount_to_transfer = min(abs(amount), abs(amounts_by_partner[currency, sign][p]['balance'])) * sign
amount_currency_to_transfer = min(abs(amount_currency), abs(amounts_by_partner[currency, sign][p]['amount_currency'])) * sign
amount -= amount_to_transfer
amount_currency -= amount_currency_to_transfer
destination_data[p, currency, sign]['balance'] += amount_to_transfer
destination_data[p, currency, sign]['amount_currency'] += amount_currency_to_transfer
amounts_by_partner[currency, sign][p]['balance'] -= amount_to_transfer
amounts_by_partner[currency, sign][p]['amount_currency'] -= amount_currency_to_transfer
# Residual amount that couldn't be associated to another partner keeps the partner from the source line
if not currency.is_zero(abs(amount)):
destination_data[partner, currency, sign]['balance'] += amount
destination_data[partner, currency, sign]['amount_currency'] += amount_currency
# Create the destination lines
for (partner, currency, sign) in destination_data:
line_ids += [
Command.create({
'name': _('Transfer from %s', self.transfer_from_account_id.display_name),
'account_id': self.reco_account_id.id,
'partner_id': partner.id,
'currency_id': currency.id,
'amount_currency': destination_data[partner, currency, sign]['amount_currency'],
'balance': destination_data[partner, currency, sign]['balance'],
}),
]
transfer_vals = {
'journal_id': self.journal_id.id,
'company_id': self.company_id.id,
'date': self._get_date_after_lock_date() or self.date,
'line_ids': line_ids,
}
transfer_move = self.env['account.move'].create(transfer_vals)
transfer_move.action_post()
return transfer_move
def reconcile(self):
""" Reconcile selected moves, with a transfer and/or write-off move if necessary."""
self.ensure_one()
self = self.with_context(no_exchange_difference=not all(self.move_line_ids.account_id.mapped('reconcile'))) # ruff: ignore[self-or-cls-assignment]
move_lines_to_reconcile = self.move_line_ids._origin
do_transfer = self.is_transfer_required
do_write_off = self.edit_mode or (self.is_write_off_required and not self.allow_partials)
if do_transfer:
transfer_move = self.create_transfer()
lines_to_transfer = move_lines_to_reconcile \
.filtered(lambda line: line.account_id == self.transfer_from_account_id)
transfer_line_from = transfer_move.line_ids \
.filtered(lambda line: line.account_id == self.transfer_from_account_id)
transfer_line_to = transfer_move.line_ids \
.filtered(lambda line: line.account_id == self.reco_account_id)
(lines_to_transfer + transfer_line_from).reconcile()
move_lines_to_reconcile = move_lines_to_reconcile - lines_to_transfer + transfer_line_to
if do_write_off:
write_off_move = self.create_write_off()
write_off_line_to_reconcile = write_off_move.line_ids[0]
move_lines_to_reconcile += write_off_line_to_reconcile
amls_plan = [[move_lines_to_reconcile, write_off_line_to_reconcile]]
else:
amls_plan = [move_lines_to_reconcile]
self.env['account.move.line']._reconcile_plan(amls_plan)
return move_lines_to_reconcile if not do_transfer else (move_lines_to_reconcile + transfer_move.line_ids)
def reconcile_open(self):
""" Reconcile selected move lines and open them in dedicated view. """
self.ensure_one()
return self.reconcile().open_reconcile_view()

View File

@@ -0,0 +1,122 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="view_account_reconcile_wizard" model="ir.ui.view">
<field name="name">account.reconcile.wizard.form</field>
<field name="model">account.reconcile.wizard</field>
<field name="arch" type="xml">
<form>
<field name="company_id" invisible="1"/>
<field name="move_line_ids" invisible="1"/>
<field name="company_currency_id" invisible="1"/>
<field name="single_currency_mode" invisible="1"/>
<field name="is_write_off_required" invisible="1"/>
<field name="is_transfer_required" invisible="1"/>
<field name="display_allow_partials" invisible="1"/>
<field name="force_partials" invisible="1"/>
<field name="is_rec_pay_account" invisible="1"/>
<field name="edit_mode" invisible="1"/>
<field name="reco_model_autocomplete_ids" invisible="1"/>
<!-- Warnings -->
<div class="alert alert-warning" role="alert" invisible="not is_transfer_required">
<field name="transfer_warning_message"/>
</div>
<div class="alert alert-warning" role="alert" invisible="not lock_date_violated_warning_message">
<field name="lock_date_violated_warning_message"/>
</div>
<div class="alert alert-warning" role="alert" invisible="not force_partials">
<p>Only partial reconciliation is possible. Proceed in multiple steps if you want to full reconcile.</p>
</div>
<!-- Reco models -->
<field name="reco_model_id" nolabel="1"
domain="[['id', 'in', reco_model_autocomplete_ids]]"
widget="badges_many2one"
invisible="not reco_model_autocomplete_ids and not reco_model_id"/>
<group>
<!-- Left side of the form -->
<group>
<field name="allow_partials" invisible="not display_allow_partials" readonly="force_partials"/>
<field name="account_id"
required="not allow_partials or edit_mode"
invisible="allow_partials and not edit_mode"/>
<field name="to_partner_id"
required="not allow_partials or edit_mode"
invisible="not is_rec_pay_account or (allow_partials and not edit_mode)"/>
<field name="tax_id"
context="{'append_fields': ['type_tax_use']}"
invisible="allow_partials and not edit_mode"/>
<field name="journal_id"
required="not allow_partials or edit_mode"
invisible="allow_partials and not edit_mode"/>
<field name="label"
required="not allow_partials or edit_mode"
invisible="allow_partials and not edit_mode"/>
</group>
<!-- Right side of the form-->
<group invisible="allow_partials and not edit_mode">
<div class="o_td_label">
<label for="amount_currency"
string="Amount"
class="o_form_label"
invisible="edit_mode"/>
<label for="edit_mode_amount_currency"
string="Amount"
class="o_form_label"
invisible="not edit_mode"/>
</div>
<div class="d-flex">
<div name="regular_mode_amounts" invisible="edit_mode">
<div name="amount_div" class="d-flex o-row" style="white-space: pre;">
<div name="amount_currency_div" class="d-flex o-row">
<field name="amount_currency"
required="not allow_partials and not edit_mode"
options="{'no_symbol': True}"
class="oe_inline"/>
<span class="oe_inline o_form_label mx-3"
invisible="reco_currency_id == company_currency_id"> in </span>
<field name="reco_currency_id"
invisible="reco_currency_id == company_currency_id"
class="oe_inline"/>
</div>
<div name="amount_company_div"
class="d-flex o-row"
invisible="reco_currency_id == company_currency_id">
<span> (</span>
<field name="amount" widget="float"/>
<span> </span>
<field name="company_currency_id" nolabel="1"/>
<span>)</span>
</div>
</div>
</div>
<div name="edit_mode_amounts" invisible="not edit_mode">
<field name="edit_mode_amount_currency"
required="edit_mode"
options="{'no_symbol': True}"
class="oe_inline"/>
<span class="oe_inline o_form_label mx-3"
invisible="single_currency_mode"> in </span>
<field name="reco_currency_id"
invisible="single_currency_mode"
class="oe_inline"/>
</div>
</div>
<field name="date" required="not allow_partials or edit_mode"/>
<field name="to_check"/>
<field name="analytic_distribution"
widget="analytic_distribution"
groups="analytic.group_analytic_accounting"/>
</group>
</group>
<footer>
<button string="Reconcile" class="btn-primary" name="reconcile" type="object" data-hotkey="q"/>
<button string="Reconcile &amp; open" class="btn-primary" name="reconcile_open" type="object" data-hotkey="o"/>
<button special="cancel" data-hotkey="x"/>
</footer>
</form>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,51 @@
from odoo import fields, models
from odoo.tools import SQL
class AccountSelectAccountLine(models.TransientModel):
_name = "account.select.account.line"
_description = "Account Select Account Line"
# Unused wizard but can't remove in stable
name = fields.Char()
code = fields.Char()
description = fields.Char()
account_type = fields.Selection(
selection=[
("asset_receivable", "Receivable"),
("asset_cash", "Bank and Cash"),
("asset_current", "Current Assets"),
("asset_non_current", "Non-current Assets"),
("asset_prepayments", "Prepayments"),
("asset_fixed", "Fixed Assets"),
("liability_payable", "Payable"),
("liability_credit_card", "Credit Card"),
("liability_current", "Current Liabilities"),
("liability_non_current", "Non-current Liabilities"),
("equity", "Equity"),
("equity_unaffected", "Current Year Earnings"),
("income", "Income"),
("income_other", "Other Income"),
("expense", "Expenses"),
("expense_other", "Other Expenses"),
("expense_depreciation", "Depreciation"),
("expense_direct_cost", "Cost of Revenue"),
("off_balance", "Off-Balance Sheet"),
],
)
amount = fields.Monetary(currency_field='currency_id')
currency_id = fields.Many2one('res.currency')
account_id = fields.Many2one('account.account')
def _order_to_sql(self, table, order, reverse=False):
sql_order = super()._order_to_sql(table, order, reverse)
if order == self._order and (preferred_account_type := self.env.context.get('preferred_account_type')):
sql_order = SQL(
"%(field_sql)s = %(preferred_account_type)s %(direction)s, %(base_order)s",
field_sql=table.account_type,
preferred_account_type=preferred_account_type,
direction=SQL('ASC') if reverse else SQL('DESC'),
base_order=sql_order,
)
return sql_order

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="view_account_select_account_line_tree" model="ir.ui.view">
<field name="name">account.select.account.line.tree</field>
<field name="model">account.select.account.line</field>
<field name="arch" type="xml">
<list js_class="bank_rec_account_dialog_list" editable="top" create="false" string="Accounts">
<field name="code" readonly="True"/>
<field name="name" readonly="True"/>
<field name="description" readonly="True" optional="show"/>
<field name="amount" optional="show"/>
<!-- Needed for the monetary field -->
<field name="currency_id" column_invisible="True"/>
</list>
</field>
</record>
<record id="view_select_account_search_bank_rec_widget" model="ir.ui.view">
<field name="name">account.select.account.line.search</field>
<field name="model">account.select.account.line</field>
<field name="arch" type="xml">
<search>
<field name="code"/>
<field name="name"/>
<field name="description"/>
</search>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,97 @@
from odoo import _, api, fields, models
from odoo.exceptions import UserError
class AccountSplitJournalItemWizard(models.TransientModel):
_name = 'account.split.journal.item.wizard'
_description = "Wizard that splits journal items into multiple journal items"
line_ids = fields.Many2many('account.move.line', 'account_split_journal_item_move_line_rel', 'wizard_id', 'line_id')
line_currency_id = fields.Many2one(comodel_name='res.currency')
quantity = fields.Integer(string="Quantity")
amount = fields.Monetary(string="Amount", currency_field='line_currency_id')
account_id = fields.Many2one(comodel_name='account.account', string="Account")
show_simple_wizard = fields.Boolean(compute='_compute_show_simple_wizard')
@api.depends('quantity', 'line_ids')
def _compute_show_simple_wizard(self):
for wizard in self:
wizard.show_simple_wizard = wizard.quantity != 2 or len(wizard.line_ids) > 1
@api.onchange('quantity')
def _onchange_quantity(self):
for wizard in self:
if len(wizard.line_ids) == 1 and wizard.quantity:
wizard.amount = abs(wizard.line_ids.balance) / wizard.quantity
@api.model
def default_get(self, fields):
defaults = super().default_get(fields)
self = self.browse() # noqa: PLW0642
if defaults.get('line_ids'):
line_ids = self._fields['line_ids'].convert_to_cache(defaults.get('line_ids'), self)
if lines := self.env['account.move.line'].browse(line_ids):
if not all(move.state == 'draft' for move in lines.move_id):
raise UserError(_("Selected lines should only be part of moves in draft."))
if len(lines) == 1:
defaults['quantity'] = int(lines.quantity) if lines.quantity > 1 else 2
defaults['line_currency_id'] = lines.currency_id.id
defaults['amount'] = abs(lines.balance) / defaults['quantity']
defaults['account_id'] = lines.account_id.id
else:
defaults['quantity'] = 2
return defaults
def split(self):
self.ensure_one()
if self.quantity <= 1:
raise UserError(_("Quantity must be greater than 1."))
if len(self.line_ids) == 1 and self.quantity == 2:
original_balance = abs(self.line_ids.balance)
if not (0 < self.amount < original_balance):
raise UserError(_("The split amount must be strictly between 0 and the original line amount."))
container = {'records': self.line_ids.move_id}
with (
self.env['account.move']._check_balanced(container),
self.env['account.move']._sync_dynamic_lines(container),
):
new_lines_vals = []
for line in self.line_ids:
fname = (
'balance' if line.move_id.move_type == 'entry' else
'price_unit' if not self.show_simple_wizard else
'quantity'
)
convert_to_cache = line._fields[fname].convert_to_cache # round according to the field
if not self.show_simple_wizard:
split_amount = convert_to_cache(line[fname] * self.amount / abs(line.balance), line)
orig_amount = convert_to_cache(line[fname] - split_amount, line)
vals_list = [
{fname: orig_amount, 'account_id': line.account_id.id},
{fname: split_amount, 'account_id': self.account_id.id},
]
else:
running_amount = line[fname]
vals_list = []
for i in range(self.quantity):
running_amount -= (current_amount := convert_to_cache(running_amount / (self.quantity - i), line))
vals_list.append({fname: current_amount, 'account_id': line.account_id.id})
line.write(vals_list[0])
for vals in vals_list[1:]:
new_lines_vals.append(line.copy_data(vals | {
fname: val
for fname in ('deferred_start_date', 'deferred_end_date')
if (val := line[fname])
})[0])
self.env['account.move.line'].create(new_lines_vals)

View File

@@ -0,0 +1,23 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="account_split_journal_item_view" model="ir.ui.view">
<field name="name">Split Journal Item</field>
<field name="model">account.split.journal.item.wizard</field>
<field name="arch" type="xml">
<form string="Split Journal Item">
<field name="line_ids" invisible="1"/> <!-- Needed to fill the fields correctly -->
<field name="line_currency_id" invisible="1"/> <!-- Needed for monetary widget -->
<group>
<field name="quantity"/>
<field name="amount" invisible="show_simple_wizard"/>
<field name="account_id" invisible="show_simple_wizard"/>
</group>
<footer>
<button string="Split" name="split" type="object" default_focus="1" class="btn-primary" data-hotkey="s"/>
<button string="Discard" class="btn-secondary" special="cancel" data-hotkey="x"/>
</footer>
</form>
</field>
</record>
</odoo>

View File

@@ -0,0 +1,53 @@
from odoo import fields, models
class BankRecAutoReconcileWizard(models.TransientModel):
_name = 'bank.rec.auto.reconcile.wizard'
_description = 'Bank Reconciliation Auto Reconcile Wizard'
date = fields.Date(
string="Start Date",
default=lambda self: fields.Date.subtract(fields.Date.today(), months=1),
)
journal_id = fields.Many2one(
comodel_name='account.journal',
string="Journal",
domain="[('type', 'in', ('bank', 'cash', 'credit'))]",
)
def action_auto_reconcile(self):
self.ensure_one()
st_lines = self.env['account.bank.statement.line'].search([
('journal_id', '=', self.journal_id.id),
('date', '>=', self.date),
('date', '<=', fields.Date.today()),
('is_reconciled', '=', False),
('state', '!=', 'cancel'),
])
if not st_lines:
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'type': 'warning',
'message': self.env._('Nothing to reconcile.'),
},
}
st_lines._try_auto_reconcile_statement_lines()
return {
'type': 'ir.actions.client',
'tag': 'display_notification',
'params': {
'type': 'success',
'message': self.env._("Automatic reconciliation finished."),
'next': {
'type': 'ir.actions.client',
'tag': 'bank_rec_reload_reconciled_lines',
'params': {
'reconciled_ids': st_lines.filtered('is_reconciled').ids,
},
},
},
}

View File

@@ -0,0 +1,24 @@
<?xml version="1.0" encoding="utf-8"?>
<odoo>
<record id="bank_rec_auto_reconcile_wizard_view_form" model="ir.ui.view">
<field name="name">bank.rec.auto.reconcile.wizard.form</field>
<field name="model">bank.rec.auto.reconcile.wizard</field>
<field name="arch" type="xml">
<form string="Run Auto Reconciliation">
<p>
Choose a journal and a starting date. The system will try to automatically
reconcile all unreconciled bank statement lines from that date until today.
</p>
<group>
<field name="journal_id" required="1" options="{'no_quick_create':True,'no_create_edit':True}"/>
<field name="date" required="1"/>
</group>
<footer>
<button string="Run" data-hotkey="q" name="action_auto_reconcile" type="object" class="btn-primary"/>
<button string="Cancel" class="btn-secondary" special="cancel" data-hotkey="z"/>
</footer>
</form>
</field>
</record>
</odoo>