From 453b5cee213740008ce5ca1db7539a4ffa80d823 Mon Sep 17 00:00:00 2001 From: Mihir Kandoi Date: Tue, 23 Jun 2026 17:09:58 +0530 Subject: [PATCH] fix(stock): guard batchwise valuation-rate division against a zero divisor (Postgres) (#56361) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit fix(stock): guard batchwise valuation-rate division against a zero divisor get_valuation_rate's batchwise fallback selects Sum(stock_value_difference) / Sum(actual_qty). When a batch's non-current Stock Ledger Entries net to zero quantity (equal received and issued) the divisor Sum(actual_qty) is 0. On MariaDB x/0 yields NULL and the caller's `if last_valuation_rate and last_valuation_rate[0][0] is not None` check falls through to the next strategy; on PostgreSQL float division by zero raises `division by zero`, aborting the query (and the transaction). Wrap the divisor in NullIf(Sum(actual_qty), 0) so a zero divisor yields NULL on both engines, matching MariaDB and preserving the caller's is-not-None fall-through. (stock_value_difference is Currency and actual_qty is Float, so the division was already float — no integer-truncation change.) --- erpnext/stock/stock_ledger.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/erpnext/stock/stock_ledger.py b/erpnext/stock/stock_ledger.py index 30e0772b15c..0b2093fe765 100644 --- a/erpnext/stock/stock_ledger.py +++ b/erpnext/stock/stock_ledger.py @@ -10,7 +10,7 @@ import frappe from frappe import _, bold, scrub from frappe.model.meta import get_field_precision from frappe.query_builder import Order -from frappe.query_builder.functions import Lower, Sum +from frappe.query_builder.functions import Lower, NullIf, Sum from frappe.utils import ( cint, flt, @@ -1975,7 +1975,7 @@ def get_valuation_rate( table = frappe.qb.DocType("Stock Ledger Entry") query = ( frappe.qb.from_(table) - .select(Sum(table.stock_value_difference) / Sum(table.actual_qty)) + .select(Sum(table.stock_value_difference) / NullIf(Sum(table.actual_qty), 0)) .where( (table.item_code == item_code) & (table.warehouse == warehouse)