Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,20 @@ List<Object[]> 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<Object> lockForUpdate(@Param("ids") List<Long> ids);

List<ItemStockEntry> findByItemStockEntryIDIn(List<Long> comapreid);

@Query(nativeQuery = true, value = "select van.vanID from m_facility fac left join m_van van on fac.facilityID=van.facilityID"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);

}
Original file line number Diff line number Diff line change
Expand Up @@ -44,4 +44,11 @@ public interface StockAdjustmentItemRepo extends CrudRepository<StockAdjustmentI

List<StockAdjustmentItem> 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<Object[]> findRecentAdjustmentItems(@Param("facilityID") Integer facilityID, @Param("seconds") Integer seconds);

}
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -143,59 +145,118 @@
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 {

Check failure on line 155 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Refactor this method to reduce its Cognitive Complexity from 17 to the 15 allowed.

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMQ&open=AaHuckWiC9cZUl-G7AMQ&pullRequest=140
List<StockAdjustmentItem> sd = stockAdjustment.getStockAdjustmentItem();
if (sd == null || sd.isEmpty())
throw new InventoryException("No item found to adjust");
stockAdjustment.setStockAdjustmentItem(null);

List<Long> comapreid = new ArrayList<>();
final Integer facID = stockAdjustment.getFacilityID();
sd.parallelStream().forEach(action -> {
comapreid.add(action.getItemStockEntryID());
List<Long> entryIDs = new ArrayList<>();
for (StockAdjustmentItem action : sd) {
action.setFacilityID(facID);
});
action.setSyncFacilityID(facID);
entryIDs.add(action.getItemStockEntryID());
}

List<ItemStockEntry> 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<Integer, ItemStockEntry> 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<Integer, ...> looked up with
// the item's Long id never matched, so this check never ran before.
Map<Long, ItemStockEntry> 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<StockAdjustmentItem> items) {
if (facID == null)
return false;

List<String> incoming = new ArrayList<>();
for (StockAdjustmentItem item : items)
incoming.add(itemKey(item.getItemStockEntryID(), Boolean.TRUE.equals(item.getIsAdded()),
item.getAdjustedQuantity()));
Collections.sort(incoming);

Check warning on line 230 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this "Collections.sort()" with "List.sort()".

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMR&open=AaHuckWiC9cZUl-G7AMR&pullRequest=140

Map<String, List<String>> 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<String> saved : recent.values()) {
Collections.sort(saved);

Check warning on line 238 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this "Collections.sort()" with "List.sort()".

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMS&open=AaHuckWiC9cZUl-G7AMS&pullRequest=140
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)

Check warning on line 251 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this instanceof check and cast with 'instanceof Boolean boolean'

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMT&open=AaHuckWiC9cZUl-G7AMT&pullRequest=140
return (Boolean) value;
if (value instanceof Number)

Check warning on line 253 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this instanceof check and cast with 'instanceof Number number'

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMU&open=AaHuckWiC9cZUl-G7AMU&pullRequest=140
return ((Number) value).intValue() == 1;
if (value instanceof byte[])

Check warning on line 255 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this instanceof check and cast with 'instanceof byte[] byteArray'

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMV&open=AaHuckWiC9cZUl-G7AMV&pullRequest=140

Check warning on line 255 in src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Replace this instanceof check and cast with 'instanceof byte[] byteArray'

See more on https://sonarcloud.io/project/issues?id=PSMRI_Inventory-API&issues=AaHuckWiC9cZUl-G7AMW&open=AaHuckWiC9cZUl-G7AMW&pullRequest=140
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();

Expand Down
Loading