From f9f5531f3fd43240b1c32ce6e350fa8fefd9dc5f Mon Sep 17 00:00:00 2001 From: Toufik Ben Jaa Date: Mon, 24 Feb 2020 15:40:17 +0000 Subject: [PATCH] [FIX] sale: speed-up invoice creation - At invoice creation, the stored fields that depends on `invoice_lines` are computed to be stored. This can slow down the invoice creation for a database with a lot of records on `account_move`. This commit speed-up the invoice creation by using SQL Joins to speed-up the searches. We cannot use `auto_join` on the `invoice_lines` field since it is not supported on many2many, thus we do it in SQL. closes odoo/odoo#46233 X-original-commit: b39e17c464775564faa7d0f10e675d47fa026234 Signed-off-by: Toufik Benjaa (tbe) --- addons/sale/models/sale.py | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/addons/sale/models/sale.py b/addons/sale/models/sale.py index e2fe110f2aa..06fd67db099 100644 --- a/addons/sale/models/sale.py +++ b/addons/sale/models/sale.py @@ -119,6 +119,20 @@ class SaleOrder(models.Model): order.order_line._compute_tax_id() def _search_invoice_ids(self, operator, value): + if operator == 'in' and value: + self.env.cr.execute(""" + SELECT array_agg(so.id) + FROM sale_order so + JOIN sale_order_line sol ON sol.order_id = so.id + JOIN sale_order_line_invoice_rel soli_rel ON soli_rel.order_line_id = sol.id + JOIN account_move_line aml ON aml.id = soli_rel.invoice_line_id + JOIN account_move am ON am.id = aml.move_id + WHERE + am.move_type in ('out_invoice', 'out_refund') AND + am.id = ANY(%s) + """, (list(value),)) + so_ids = self.env.cr.fetchone()[0] or [] + return [('id', 'in', so_ids)] return ['&', ('order_line.invoice_lines.move_id.move_type', 'in', ('out_invoice', 'out_refund')), ('order_line.invoice_lines.move_id', operator, value)] name = fields.Char(string='Order Reference', required=True, copy=False, readonly=True, states={'draft': [('readonly', False)]}, index=True, default=lambda self: _('New'))