diff --git a/src/main/java/com/iemr/inventory/repo/stockEntry/ItemStockEntryRepo.java b/src/main/java/com/iemr/inventory/repo/stockEntry/ItemStockEntryRepo.java index 915c2cb7..88c44118 100644 --- a/src/main/java/com/iemr/inventory/repo/stockEntry/ItemStockEntryRepo.java +++ b/src/main/java/com/iemr/inventory/repo/stockEntry/ItemStockEntryRepo.java @@ -99,6 +99,20 @@ List findByItemIDInQuantityInHandGreaterThanForFacilityID(@Param("item @Query("UPDATE ItemStockEntry c SET c.quantityInHand = c.quantityInHand - :quant WHERE c.itemStockEntryID = :id") Integer subtractStock(@Param("id") Long id, @Param("quant") Integer quant); + // Takes the stock out only if the batch still holds enough; returns 0 otherwise, + // so stock in hand can never go below zero. + @Transactional + @Modifying + @Query("UPDATE ItemStockEntry c SET c.quantityInHand = c.quantityInHand - :quant " + + "WHERE c.itemStockEntryID = :id AND c.quantityInHand >= :quant") + Integer subtractStockIfAvailable(@Param("id") Long id, @Param("quant") Integer quant); + + // Row-locks the batches for the rest of the transaction. A second request touching + // the same batches waits here until the first one has committed. + @Query(value = "SELECT ItemStockEntryID FROM t_itemstockentry WHERE ItemStockEntryID IN (:ids) FOR UPDATE", + nativeQuery = true) + List lockForUpdate(@Param("ids") List ids); + List findByItemStockEntryIDIn(List comapreid); @Query(nativeQuery = true, value = "select van.vanID from m_facility fac left join m_van van on fac.facilityID=van.facilityID" diff --git a/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentDraftRepo.java b/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentDraftRepo.java index 2474be0a..043dbeb5 100644 --- a/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentDraftRepo.java +++ b/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentDraftRepo.java @@ -57,4 +57,12 @@ Integer updateStock(@Param("id") Long id, @Param("draftDesc") String draftDesc,@ @Query("UPDATE StockAdjustmentDraft c SET c.isCompleted = :isCompleted WHERE c.stockAdjustmentDraftID = :id") Integer updatecompleted(@Param("id")Long stockAdjustmentDraftID,@Param("isCompleted") boolean b); + // Marks the draft completed only if it is still open; returns 0 when it was already + // completed, i.e. this draft has already been saved as an adjustment. + @Transactional + @Modifying + @Query("UPDATE StockAdjustmentDraft c SET c.isCompleted = true WHERE c.stockAdjustmentDraftID = :id " + + "AND (c.isCompleted IS NULL OR c.isCompleted = false)") + Integer markCompletedIfOpen(@Param("id") Long stockAdjustmentDraftID); + } diff --git a/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentItemRepo.java b/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentItemRepo.java index 09b4c2e2..d5966d4b 100644 --- a/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentItemRepo.java +++ b/src/main/java/com/iemr/inventory/repo/stockadjustment/StockAdjustmentItemRepo.java @@ -44,4 +44,11 @@ public interface StockAdjustmentItemRepo extends CrudRepository findByStockAdjustmentIDAndSyncFacilityID(Long vanSerialNo, Integer syncFacilityID); + // Items of the facility's adjustments saved in the last :seconds seconds. A locking + // read, so it sees an adjustment another request committed a moment ago. + @Query(value = "SELECT StockAdjustmentID, ItemStockEntryID, IsAdded, AdjustedQuantity FROM t_saitemmapping " + + "WHERE FacilityID = :facilityID AND IFNULL(Deleted, 0) = 0 " + + "AND CreatedDate >= NOW() - INTERVAL :seconds SECOND LOCK IN SHARE MODE", nativeQuery = true) + List findRecentAdjustmentItems(@Param("facilityID") Integer facilityID, @Param("seconds") Integer seconds); + } diff --git a/src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java b/src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java index fe002032..be080cff 100644 --- a/src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java +++ b/src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java @@ -23,6 +23,8 @@ import java.sql.Timestamp; import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.function.Function; @@ -143,59 +145,118 @@ public StockAdjustmentDraft getforeditStockAjustmentDraftTransaction(Long stockA return stock; } + // An identical adjustment for the same facility within this many seconds is treated + // as a repeated submit (double click / retry) of one already saved. + private static final int DUPLICATE_WINDOW_SECONDS = 120; + + private static final String ALREADY_SAVED = "This stock adjustment has already been saved"; + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public StockAdjustment savetransaction(StockAdjustment stockAdjustment) throws InventoryException { List sd = stockAdjustment.getStockAdjustmentItem(); + if (sd == null || sd.isEmpty()) + throw new InventoryException("No item found to adjust"); stockAdjustment.setStockAdjustmentItem(null); - List comapreid = new ArrayList<>(); final Integer facID = stockAdjustment.getFacilityID(); - sd.parallelStream().forEach(action -> { - comapreid.add(action.getItemStockEntryID()); + List entryIDs = new ArrayList<>(); + for (StockAdjustmentItem action : sd) { action.setFacilityID(facID); - }); + action.setSyncFacilityID(facID); + entryIDs.add(action.getItemStockEntryID()); + } - List compareobject = itemStockEntryRepo.findByItemStockEntryIDIn(comapreid); + // Lock the batches first, so a repeated submit of this adjustment waits until this + // one commits, and then sees it in the checks below. + itemStockEntryRepo.lockForUpdate(entryIDs); - Map result = compareobject.stream() - .collect(Collectors.toMap(ItemStockEntry::getItemStockEntryID, Function.identity())); + // A draft can be turned into an adjustment only once. + if (stockAdjustment.getStockAdjustmentDraftID() != null + && stockAdjustmentDraftRepo.markCompletedIfOpen(stockAdjustment.getStockAdjustmentDraftID()) == 0) + throw new InventoryException(ALREADY_SAVED); - for (StockAdjustmentItem action : sd) { - action.setSyncFacilityID(facID); - ItemStockEntry itemStockEntry = result.get(action.getItemStockEntryID()); + if (isRepeatOfRecentAdjustment(facID, sd)) + throw new InventoryException(ALREADY_SAVED); - if (!action.getIsAdded()) { - if (null != itemStockEntry && action.getAdjustedQuantity() > itemStockEntry.getQuantityInHand()) { - throw new InventoryException( - "Adjustment Quantity for issue should be more than available quantity"); - } - } + // Keyed by Long: ItemStockEntry's id is an int, and a Map looked up with + // the item's Long id never matched, so this check never ran before. + Map batches = itemStockEntryRepo.findByItemStockEntryIDIn(entryIDs).stream() + .collect(Collectors.toMap(e -> (long) e.getItemStockEntryID(), Function.identity())); + + for (StockAdjustmentItem action : sd) { + ItemStockEntry batch = batches.get(action.getItemStockEntryID()); + if (batch == null) + throw new InventoryException("Batch " + action.getItemStockEntryID() + " not found"); + if (!Boolean.TRUE.equals(action.getIsAdded()) && batch.getQuantityInHand() != null + && action.getAdjustedQuantity() > batch.getQuantityInHand()) + throw new InventoryException("Adjustment quantity for issue cannot be more than the available quantity"); } stockAdjustment.setSyncFacilityID(facID); stockAdjustmentRepo.save(stockAdjustment); stockAdjustmentRepo.updateVanSerialNo(); + // Sequential, not parallelStream: worker threads do not join this transaction, so + // their stock updates were not rolled back when a later step failed. Long saID = stockAdjustment.getStockAdjustmentID(); - sd.parallelStream().forEach(action -> { + for (StockAdjustmentItem action : sd) { action.setStockAdjustmentID(saID); - if (action.getIsAdded()) { - itemStockEntryRepo.addStock(action.getItemStockEntryID(), action.getAdjustedQuantity()); - } else { - itemStockEntryRepo.subtractStock(action.getItemStockEntryID(), action.getAdjustedQuantity()); - } - - }); + int updated = Boolean.TRUE.equals(action.getIsAdded()) + ? itemStockEntryRepo.addStock(action.getItemStockEntryID(), action.getAdjustedQuantity()) + : itemStockEntryRepo.subtractStockIfAvailable(action.getItemStockEntryID(), + action.getAdjustedQuantity()); + if (updated == 0) + throw new InventoryException("Adjustment quantity for issue cannot be more than the available quantity"); + } stockAdjustmentItemRepo.saveAll(sd); stockAdjustmentItemRepo.updateVanSerialNo(); stockAdjustment.setStockAdjustmentItem(sd); - if (stockAdjustment.getStockAdjustmentDraftID() != null) { - stockAdjustmentDraftRepo.updatecompleted(stockAdjustment.getStockAdjustmentDraftID(), true); - } return stockAdjustment; } + /** + * True when the facility already saved an adjustment with exactly these items + * (batch, receipt/issue, quantity) within the last DUPLICATE_WINDOW_SECONDS. + */ + private boolean isRepeatOfRecentAdjustment(Integer facID, List items) { + if (facID == null) + return false; + + List incoming = new ArrayList<>(); + for (StockAdjustmentItem item : items) + incoming.add(itemKey(item.getItemStockEntryID(), Boolean.TRUE.equals(item.getIsAdded()), + item.getAdjustedQuantity())); + Collections.sort(incoming); + + Map> recent = new HashMap<>(); + for (Object[] row : stockAdjustmentItemRepo.findRecentAdjustmentItems(facID, DUPLICATE_WINDOW_SECONDS)) + recent.computeIfAbsent(String.valueOf(row[0]), k -> new ArrayList<>()) + .add(itemKey(row[1], isTrue(row[2]), row[3])); + + for (List saved : recent.values()) { + Collections.sort(saved); + if (saved.equals(incoming)) + return true; + } + return false; + } + + private static String itemKey(Object itemStockEntryID, boolean isAdded, Object quantity) { + return itemStockEntryID + "|" + isAdded + "|" + quantity; + } + + // IsAdded comes back from the native query as Boolean, a number or a BIT byte array. + private static boolean isTrue(Object value) { + if (value instanceof Boolean) + return (Boolean) value; + if (value instanceof Number) + return ((Number) value).intValue() == 1; + if (value instanceof byte[]) + return ((byte[]) value).length > 0 && ((byte[]) value)[0] == 1; + return value != null && ("1".equals(value.toString()) || "true".equalsIgnoreCase(value.toString())); + } + public StockAdjustment getforeditStockAjustmentTransaction(Long stockAdjustmentID) { StockAdjustment stock = stockAdjustmentRepo.findById(stockAdjustmentID).get();