From a7539b366e0f813be06fb7d54a2aec60e42258d2 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Thu, 19 Nov 2026 02:35:01 +0000 Subject: [PATCH] TASK-62: batch-load inventory items in getQuantityOnHandByInventoryItem (remove N+1) Co-Authored-By: taylor.curran --- .../inventory/ProductAvailabilityService.groovy | 14 ++++++++++---- 1 file changed, 10 insertions(+), 4 deletions(-) diff --git a/grails-app/services/org/pih/warehouse/inventory/ProductAvailabilityService.groovy b/grails-app/services/org/pih/warehouse/inventory/ProductAvailabilityService.groovy index 18412aca161..797cd468878 100644 --- a/grails-app/services/org/pih/warehouse/inventory/ProductAvailabilityService.groovy +++ b/grails-app/services/org/pih/warehouse/inventory/ProductAvailabilityService.groovy @@ -877,16 +877,22 @@ class ProductAvailabilityService { } List results = ProductAvailability.createCriteria().list { projections { - resultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP) - groupProperty("inventoryItem", "inventoryItem") - sum("quantityOnHand", "quantityOnHand") + groupProperty("inventoryItem.id") + sum("quantityOnHand") } eq("location", location) if (inventoryItems) { 'in'("inventoryItem.id", inventoryItems.id) } } - return results.inject([:]) { map, it -> map << [(it.inventoryItem): it.quantityOnHand] } + // Load the grouped inventory items (and their products) in batches instead of one select per row + Map inventoryItemsById = [:] + results.collect { it[0] }.collate(1000).each { List ids -> + InventoryItem.executeQuery("select ii from InventoryItem ii left join fetch ii.product where ii.id in (:ids)", [ids: ids]).each { + inventoryItemsById[it.id] = it + } + } + return results.inject([:]) { map, it -> map << [(inventoryItemsById[it[0]]): it[1]] } } List getAvailableBinLocations(Location location, String productId) {