From e1b0c385c60bb760f8dd59d4d7b3bfe8a83c2400 Mon Sep 17 00:00:00 2001 From: Carlos Dauden Date: Fri, 3 Feb 2017 22:11:17 +0100 Subject: [PATCH] [9.0][IMP] partner_sale_risk: Improve performance --- partner_sale_risk/models/res_partner.py | 16 +++++++++++++--- partner_sale_risk/models/sale.py | 21 +++++++++++++++------ 2 files changed, 28 insertions(+), 9 deletions(-) diff --git a/partner_sale_risk/models/res_partner.py b/partner_sale_risk/models/res_partner.py index f5d669ebd..4a322a5ff 100644 --- a/partner_sale_risk/models/res_partner.py +++ b/partner_sale_risk/models/res_partner.py @@ -18,11 +18,21 @@ class ResPartner(models.Model): help='Total not invoiced of sales orders in Sale Order state') @api.multi - @api.depends('sale_order_ids', 'sale_order_ids.invoice_pending_amount') + @api.depends('sale_order_ids', 'sale_order_ids.invoice_pending_amount', + 'child_ids.sale_order_ids', + 'child_ids.sale_order_ids.invoice_pending_amount') def _compute_risk_sale_order(self): - for partner in self: + customers = self.filtered('customer') + partners = customers | customers.mapped('child_ids') + orders_group = self.env['sale.order'].read_group( + [('state', '=', 'sale'), ('partner_id', 'in', partners.ids)], + ['partner_id', 'invoice_pending_amount'], + ['partner_id']) + for partner in customers: + partner_ids = (partner | partner.mapped('child_ids')).ids partner.risk_sale_order = sum( - partner.sale_order_ids.mapped('invoice_pending_amount')) + [x['invoice_pending_amount'] + for x in orders_group if x['partner_id'][0] in partner_ids]) @api.model def _risk_field_list(self): diff --git a/partner_sale_risk/models/sale.py b/partner_sale_risk/models/sale.py index c79494936..eaa10c4d6 100644 --- a/partner_sale_risk/models/sale.py +++ b/partner_sale_risk/models/sale.py @@ -16,17 +16,26 @@ class SaleOrder(models.Model): @api.multi @api.depends('state', 'order_line.invoice_lines.invoice_id.amount_total') def _compute_invoice_amount(self): + AccountInvoice = self.env['account.invoice'] for order in self.filtered(lambda x: x.state == 'sale'): - order.invoice_amount = sum( - order.invoice_ids.mapped('amount_total')) - order.invoice_pending_amount = ( - order.amount_total > order.invoice_amount and - order.amount_total - order.invoice_amount or 0.0) + invoice_ids = order.order_line.mapped('invoice_lines').mapped( + 'invoice_id').ids + if not invoice_ids: + continue + amount = AccountInvoice.read_group( + [('id', 'in', invoice_ids), + ('type', 'in', ['out_invoice', 'out_refund'])], + ['amount_total'], + [] + )[0]['amount_total'] + order.invoice_amount = amount + if order.amount_total > amount: + order.invoice_pending_amount = order.amount_total - amount @api.multi def action_confirm(self): if not self.env.context.get('bypass_risk', False): - partner = self.partner_id + partner = self.partner_id.commercial_partner_id exception_msg = "" if partner.risk_exception: exception_msg = _("Financial risk exceeded.\n")