From 8b04c1d4f6356bc332c5dd8f6f8711d778e030cd Mon Sep 17 00:00:00 2001 From: ruthra kumar Date: Wed, 22 Nov 2023 09:59:32 +0530 Subject: [PATCH] refactor: optimize outstanding vouchers query --- erpnext/accounts/utils.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/erpnext/accounts/utils.py b/erpnext/accounts/utils.py index 7d91309fcced..6d2a47f73e6f 100644 --- a/erpnext/accounts/utils.py +++ b/erpnext/accounts/utils.py @@ -1833,6 +1833,28 @@ def query_for_outstanding(self): Table("outstanding").amount_in_account_currency >= self.max_outstanding ) + if self.limit and self.get_invoices: + outstanding_vouchers = ( + qb.from_(ple) + .select( + ple.against_voucher_no.as_("voucher_no"), + Sum(ple.amount_in_account_currency).as_("amount_in_account_currency"), + ) + .where(ple.delinked == 0) + .where(Criterion.all(filter_on_against_voucher_no)) + .where(Criterion.all(self.common_filter)) + .groupby(ple.against_voucher_type, ple.against_voucher_no, ple.party_type, ple.party) + .orderby(ple.posting_date, ple.voucher_no) + .having(qb.Field("amount_in_account_currency") > 0) + .limit(self.limit) + .run() + ) + if outstanding_vouchers: + filter_on_voucher_no.append(ple.voucher_no.isin([x[0] for x in outstanding_vouchers])) + filter_on_against_voucher_no.append( + ple.against_voucher_no.isin([x[0] for x in outstanding_vouchers]) + ) + # build query for voucher amount query_voucher_amount = ( qb.from_(ple)