TLDR:
* invoices are implemented using computed methods instead of onchange
* the synchronization only happens when switching tabs in the Form view
to improve perfs.
_______________________________________________________________________
The whole engine of the synchronization of Invoices to the Journal
Entries has been refactored
* by using computed fields instead of onchange functions
* by synchronizing only from invoice to journal entry in `create` and
`write`
* by saving when switching tabs on the Invoice form, to synchronize
before showing the values
This comes with numerous advantages:
* no need to call the onchange methods manually
* no need to use the Form emulator to build invoices (i.e. EDI, OCR,
intercompany, ...)
* the performance for invoices with many lines improves drastically, going
from 2 minutes to 4 seconds to create an invoice with 500 lines
* the model is more declarative, we can now see how the values are computed
instead of having the values being copied from various places.
* remove the hack in `onchange` that disabled the recursivity of it,
which was unexpected and needed to be managed manually in all the
onchange methods
This means that:
* Some fields need to be exclusively computed on journal entries values
or invoice values, more specifically the Tax Summary widget.
It is now
- computed from entry lines, when opening the view
- computed from invoice lines when changing those, because the tax lines
will need to be recomputed anyways, erasing previously set values
- set with an inverse function when saving; after the sync has been done
* Some possible operations previously possible have been dropped.
(i.e. look at the removed test test_in_invoice_line_onchange_accounting_fields_1)
This is because such a behavior was undefined (how is changing the balance going
to affect the unit price? How is the amount currency going to affect it?)
_______________________________________________________________________
Implementation Details
----------------------
The "dynamic lines", meaning the payment terms and the tax lines are now
only created in the `create` and `write` functions.
In order to reduce code duplication, it has been implemented using
context managers used in both `account.move` and `account.move.line`
These context managers help comparing the values before/after, acting
like a local `onchange`, but getting benefit from the dirty flags from
the `compute` dependences.
This is relying on computed fields on the move (`needed_terms`) and on
the lines (`compute_all_tax`) which contain the values needed for the
related move.
Depending on the needed values and the existing values (`term_key` and
`tax_key`, respectively) the context manager will determine what needs
to be created/updated/deleted.
Some related changes are to produce a `dict` instead of a `str` for the
`tax_totals` (previously `tax_totals_json`) fields, by simplicity to
reduce the complexity of IO, and simplicity of debugging, because the
logic of the field needed to change (cannot be computed at the same time
anymore since it needed the lines to be synced)
By simplicity, and also because it makes more sense, some boolean fields
have been merged into `display_type`:
* `is_rounding_line`
* `exclude_from_invoice_tab`
* `is_anglo_saxon_line`
The `price_unit`, `quantity` and other "invoice fields" are now not set
anymore on lines that are not product lines since it didn't make any
sense to have it.
Performances
------------
You have to keep in mind that a simple `create` didn't compute a lot of
fields, for instance not taxes were set, no payment terms,...
Now it does.
```python
import random
from timeit import timeit
from odoo import Command
domain = [('company_id', 'in', (False, self.env.company.id))]
products = self.env['product.product'].search(domain).ids
partners = self.env['res.partner'].search(domain).ids
taxes = self.env['account.tax'].search(domain).ids
def create(nmove, nline):
self.env['account.move'].create([
{
'move_type': 'out_invoice',
'partner_id': random.choice(partners),
'invoice_line_ids': [
Command.create({
'name': f'line{i}',
'product_id': random.choice(products),
'tax_ids': [Command.set([random.choice(taxes)])],
})
for i in range(nline)
]
}
for j in range(nmove)
])
# After | Before
print(timeit("create(1, 1)", globals=globals(), number=1)) # 0.11 | 0.09
print(timeit("create(100, 1)", globals=globals(), number=1)) # 2.76 | 2.50
print(timeit("create(500, 1)", globals=globals(), number=1)) # 14.56 | 12.34
print(timeit("create(1, 100)", globals=globals(), number=1)) # 1.03 | 5.52
print(timeit("create(1, 500)", globals=globals(), number=1)) # 3.99 | 125.02
print(timeit("create(50, 50)", globals=globals(), number=1)) # 19.44 | 79.55
```
Another metric that can be used is running the test suite with
`--test-tags=/account` (only `account` installed)
* before: 404s, 267127 queries (366 tests)
* after: 318s, 232125 queries (362 tests)
Why this commit title?
----------------------
Someone told me that this was the perfect way of naming your commits.
c04065abd8
task-2711317
closes odoo/odoo#96134
Related: odoo/upgrade#3715
Related: odoo/enterprise#29758
Signed-off-by: Laurent Smet <las@odoo.com>
167 lines
7.5 KiB
Python
167 lines
7.5 KiB
Python
# -*- coding: utf-8 -*-
|
|
from odoo import models, fields, api
|
|
from odoo.tools.translate import _
|
|
from odoo.exceptions import UserError
|
|
|
|
|
|
class AccountMoveReversal(models.TransientModel):
|
|
"""
|
|
Account move reversal wizard, it cancel an account move by reversing it.
|
|
"""
|
|
_name = 'account.move.reversal'
|
|
_description = 'Account Move Reversal'
|
|
_check_company_auto = True
|
|
|
|
move_ids = fields.Many2many('account.move', 'account_move_reversal_move', 'reversal_id', 'move_id', domain=[('state', '=', 'posted')])
|
|
new_move_ids = fields.Many2many('account.move', 'account_move_reversal_new_move', 'reversal_id', 'new_move_id')
|
|
date_mode = fields.Selection(selection=[
|
|
('custom', 'Specific'),
|
|
('entry', 'Journal Entry Date')
|
|
], required=True, default='custom')
|
|
date = fields.Date(string='Reversal date', default=fields.Date.context_today)
|
|
reason = fields.Char(string='Reason')
|
|
refund_method = fields.Selection(selection=[
|
|
('refund', 'Partial Refund'),
|
|
('cancel', 'Full Refund'),
|
|
('modify', 'Full refund and new draft invoice')
|
|
], string='Credit Method', required=True,
|
|
help='Choose how you want to credit this invoice. You cannot "modify" nor "cancel" if the invoice is already reconciled.')
|
|
journal_id = fields.Many2one(
|
|
comodel_name='account.journal',
|
|
string='Use Specific Journal',
|
|
required=True,
|
|
compute='_compute_journal_id',
|
|
readonly=False,
|
|
store=True,
|
|
check_company=True,
|
|
help='If empty, uses the journal of the journal entry to be reversed.',
|
|
)
|
|
company_id = fields.Many2one('res.company', required=True, readonly=True)
|
|
available_journal_ids = fields.Many2many('account.journal', compute='_compute_available_journal_ids')
|
|
country_code = fields.Char(related='company_id.country_id.code')
|
|
|
|
# computed fields
|
|
residual = fields.Monetary(compute="_compute_from_moves")
|
|
currency_id = fields.Many2one('res.currency', compute="_compute_from_moves")
|
|
move_type = fields.Char(compute="_compute_from_moves")
|
|
|
|
@api.depends('move_ids')
|
|
def _compute_journal_id(self):
|
|
for record in self:
|
|
if record.journal_id:
|
|
record.journal_id = record.journal_id
|
|
else:
|
|
journals = record.move_ids.journal_id.filtered(lambda x: x.active)
|
|
record.journal_id = journals[0] if journals else None
|
|
|
|
@api.depends('move_ids')
|
|
def _compute_available_journal_ids(self):
|
|
for record in self:
|
|
if record.move_ids:
|
|
record.available_journal_ids = self.env['account.journal'].search([
|
|
('company_id', '=', record.company_id.id),
|
|
('type', 'in', record.move_ids.journal_id.mapped('type')),
|
|
])
|
|
else:
|
|
record.available_journal_ids = self.env['account.journal'].search([('company_id', '=', record.company_id.id)])
|
|
|
|
@api.constrains('journal_id', 'move_ids')
|
|
def _check_journal_type(self):
|
|
for record in self:
|
|
if record.journal_id.type not in record.move_ids.journal_id.mapped('type'):
|
|
raise UserError(_('Journal should be the same type as the reversed entry.'))
|
|
|
|
@api.model
|
|
def default_get(self, fields):
|
|
res = super(AccountMoveReversal, self).default_get(fields)
|
|
move_ids = self.env['account.move'].browse(self.env.context['active_ids']) if self.env.context.get('active_model') == 'account.move' else self.env['account.move']
|
|
|
|
if any(move.state != "posted" for move in move_ids):
|
|
raise UserError(_('You can only reverse posted moves.'))
|
|
if 'company_id' in fields:
|
|
res['company_id'] = move_ids.company_id.id or self.env.company.id
|
|
if 'move_ids' in fields:
|
|
res['move_ids'] = [(6, 0, move_ids.ids)]
|
|
if 'refund_method' in fields:
|
|
res['refund_method'] = (len(move_ids) > 1 or move_ids.move_type == 'entry') and 'cancel' or 'refund'
|
|
return res
|
|
|
|
@api.depends('move_ids')
|
|
def _compute_from_moves(self):
|
|
for record in self:
|
|
move_ids = record.move_ids._origin
|
|
record.residual = len(move_ids) == 1 and move_ids.amount_residual or 0
|
|
record.currency_id = len(move_ids.currency_id) == 1 and move_ids.currency_id or False
|
|
record.move_type = move_ids.move_type if len(move_ids) == 1 else (any(move.move_type in ('in_invoice', 'out_invoice') for move in move_ids) and 'some_invoice' or False)
|
|
|
|
def _prepare_default_reversal(self, move):
|
|
reverse_date = self.date if self.date_mode == 'custom' else move.date
|
|
return {
|
|
'ref': _('Reversal of: %(move_name)s, %(reason)s', move_name=move.name, reason=self.reason)
|
|
if self.reason
|
|
else _('Reversal of: %s', move.name),
|
|
'date': reverse_date,
|
|
'invoice_date_due': reverse_date,
|
|
'invoice_date': move.is_invoice(include_receipts=True) and (self.date or move.date) or False,
|
|
'journal_id': self.journal_id.id,
|
|
'invoice_payment_term_id': None,
|
|
'invoice_user_id': move.invoice_user_id.id,
|
|
'auto_post': 'at_date' if reverse_date > fields.Date.context_today(self) else 'no',
|
|
}
|
|
|
|
def reverse_moves(self):
|
|
self.ensure_one()
|
|
moves = self.move_ids
|
|
|
|
# Create default values.
|
|
default_values_list = []
|
|
for move in moves:
|
|
default_values_list.append(self._prepare_default_reversal(move))
|
|
|
|
batches = [
|
|
[self.env['account.move'], [], True], # Moves to be cancelled by the reverses.
|
|
[self.env['account.move'], [], False], # Others.
|
|
]
|
|
for move, default_vals in zip(moves, default_values_list):
|
|
is_auto_post = default_vals.get('auto_post') != 'no'
|
|
is_cancel_needed = not is_auto_post and self.refund_method in ('cancel', 'modify')
|
|
batch_index = 0 if is_cancel_needed else 1
|
|
batches[batch_index][0] |= move
|
|
batches[batch_index][1].append(default_vals)
|
|
|
|
# Handle reverse method.
|
|
moves_to_redirect = self.env['account.move']
|
|
for moves, default_values_list, is_cancel_needed in batches:
|
|
new_moves = moves._reverse_moves(default_values_list, cancel=is_cancel_needed)
|
|
|
|
if self.refund_method == 'modify':
|
|
moves_vals_list = []
|
|
for move in moves.with_context(include_business_fields=True):
|
|
moves_vals_list.append(move.copy_data({'date': self.date if self.date_mode == 'custom' else move.date})[0])
|
|
new_moves = self.env['account.move'].create(moves_vals_list)
|
|
|
|
moves_to_redirect |= new_moves
|
|
|
|
self.new_move_ids = moves_to_redirect
|
|
|
|
# Create action.
|
|
action = {
|
|
'name': _('Reverse Moves'),
|
|
'type': 'ir.actions.act_window',
|
|
'res_model': 'account.move',
|
|
}
|
|
if len(moves_to_redirect) == 1:
|
|
action.update({
|
|
'view_mode': 'form',
|
|
'res_id': moves_to_redirect.id,
|
|
'context': {'default_move_type': moves_to_redirect.move_type},
|
|
})
|
|
else:
|
|
action.update({
|
|
'view_mode': 'tree,form',
|
|
'domain': [('id', 'in', moves_to_redirect.ids)],
|
|
})
|
|
if len(set(moves_to_redirect.mapped('move_type'))) == 1:
|
|
action['context'] = {'default_move_type': moves_to_redirect.mapped('move_type').pop()}
|
|
return action
|