Improve performance of get_amount() in sales and purchase modules
When we try to access the "ALL" tab in the sales list, we notice that the process slows down. Current company are:
Total sales: 1805
Total draft sales: 3 (pending cache amount)
Total quotation sales: 3 (pending cache amount)
Accessing the list of ALL sales takes 8.90 seconds.
We identified that the load comes from sale.sale.read() and the field "untaxed_amount" field.
As we can see, for most of the sales to be queried, the "amount cache" fields are already stored in database.
With the following code proposal, we see that the time is reduced to 1.57 seconds. As you can appreciate, the wait time for the user is significantly reduced.
@classmethod
def get_amount(cls, sales, names):
[...]
# Sort cached first and re-instanciate to optimize cache management
sales = sorted(sales, key=lambda s: s.state in cls._states_cached,
reverse=True)
pending = []
for sale in sales:
if (sale.state in cls._states_cached
and sale.untaxed_amount_cache is not None
and sale.tax_amount_cache is not None
and sale.total_amount_cache is not None):
untaxed_amount[sale.id] = sale.untaxed_amount_cache
if compute_taxes:
tax_amount[sale.id] = sale.tax_amount_cache
total_amount[sale.id] = sale.total_amount_cache
else:
pending.append(sale)
for sale in cls.browse(pending):
untaxed_amount[sale.id] = sum(
(line.amount for line in sale.lines
if line.type == 'line'), Decimal(0))
if compute_taxes:
tax_amount[sale.id] = sale.get_tax_amount()
total_amount[sale.id] = (
untaxed_amount[sale.id] + tax_amount[sale.id])
[...]
Edited by Cédric Krier