Skip to content

fix: resolve concurrency, data integrity, and correctness bugs in stock management#126

Open
PragyaTripathi990 wants to merge 1 commit intoPSMRI:mainfrom
PragyaTripathi990:fix/stock-concurrency-dispense-and-data-integrity
Open

fix: resolve concurrency, data integrity, and correctness bugs in stock management#126
PragyaTripathi990 wants to merge 1 commit intoPSMRI:mainfrom
PragyaTripathi990:fix/stock-concurrency-dispense-and-data-integrity

Conversation

@PragyaTripathi990
Copy link
Copy Markdown

Summary

This PR fixes 5 real bugs across the inventory and stock management services:

1. Race condition in StockAdjustmentServiceImplparallelStream on non-thread-safe collections

parallelStream was used with a shared ArrayList (not thread-safe) and with JPA @Modifying queries. Parallel threads bypass the @Transactional coordinator, making rollback unreliable and causing lost updates or corrupted stock counts under concurrent load. Fixed by converting to sequential forEach.

2. Silent dispense failure in StockExitServiceImpl

When getItemStockAndValidate filtered out items due to insufficient stock, all three exit flows (patient issue, self-consumption, store transfer) silently returned 0 with no indication of which items failed. Pharmacists had no way to know what went wrong. Fixed by throwing InventoryException naming each failed item with requested vs. available quantities.

3. Wrong column in updateStock query — ItemStockEntryRepo

The WHERE clause matched on vanSerialNo (a mutable sync field) while the caller always passed itemStockEntryID. In any record where the two diverge, stock was deducted from the wrong batch or not deducted at all. Fixed by changing the WHERE clause to use the stable primary key itemStockEntryID.

4. No atomicity or quantity guard in PatientReturnServiceImpl

Two separate DB updates (stock restore + exit quantity decrement) ran non-atomically with no upper-bound validation. A crash after the first update permanently inflated stock. A caller could also return more drugs than were dispensed. Fixed by adding @Transactional(rollbackFor = Exception.class) and a guard that rejects returnQuantity > issuedQuantity.

5. Deprecated Date mutation causing wrong expiry window — StockEntryServiceImpl

Date.setDate() and Date.setMonth() are deprecated since Java 1.1 and do not handle month-boundary overflow (e.g. Jan 31 + 1 month → Mar 3) or DST transitions, producing an incorrect expiry cutoff that could serve expired stock or reject valid batches. Fixed by replacing with java.time.LocalDate.plusDays/plusMonths/plusWeeks.

Test plan

  • Stock adjustment with multiple items completes atomically under load
  • Dispensing a drug with insufficient stock returns a clear error message with item details
  • Stock deduction hits the correct batch after updateStock
  • Returning more drugs than issued is rejected with a clear error
  • Drug dispensing with Day/Month/Week duration correctly filters expired batches at month boundaries

…ck management

1. StockAdjustmentServiceImpl - Replace parallelStream with sequential forEach
   parallelStream on a non-thread-safe ArrayList caused lost updates and
   ArrayIndexOutOfBoundsException under concurrent load. JPA @Modifying queries
   called from parallel threads also bypass the @transactional boundary, making
   rollback unreliable and causing partial stock adjustments.

2. StockExitServiceImpl - Throw InventoryException on partial stock validation failure
   When getItemStockAndValidate filtered out items due to insufficient stock, all
   three exit flows (patient issue, self-consumption, store transfer) silently
   returned 0 with no indication of which items failed. Now throws InventoryException
   naming each failed item with its requested vs. available quantities.

3. ItemStockEntryRepo - Fix updateStock query to match on itemStockEntryID not vanSerialNo
   The WHERE clause used vanSerialNo (a mutable sync field) while the caller passed
   itemStockEntryID. In any record where the two diverge, stock was deducted from the
   wrong batch or not deducted at all. Fixed to use the stable primary key.

4. PatientReturnServiceImpl - Add @transactional and quantity guard to updateQuantityReturned
   Two separate DB updates (stock restore + exit quantity decrement) ran non-atomically
   with no upper-bound check. A crash after the first update permanently inflated stock.
   A caller could also return more than was dispensed. Now @transactional ensures both
   updates roll back together, and the guard rejects returnQuantity > issuedQuantity.

5. StockEntryServiceImpl - Replace deprecated Date mutation with java.time
   Date.setDate/setMonth are deprecated since Java 1.1 and do not handle month-boundary
   overflow (e.g. Jan 31 + 1 month wraps incorrectly) or DST transitions, producing a
   wrong expiry threshold that could serve expired stock or reject valid batches.
   Replaced with LocalDate.plusDays/plusMonths/plusWeeks via java.time.
@coderabbitai
Copy link
Copy Markdown

coderabbitai Bot commented May 7, 2026

Warning

Rate limit exceeded

@PragyaTripathi990 has exceeded the limit for the number of commits that can be reviewed per hour. Please wait 36 minutes before requesting another review.

You’ve run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 1155e35c-dde1-4aac-9dab-026fbefbff13

📥 Commits

Reviewing files that changed from the base of the PR and between 62d6226 and f5ac0e0.

📒 Files selected for processing (7)
  • src/main/java/com/iemr/inventory/repo/stockEntry/ItemStockEntryRepo.java
  • src/main/java/com/iemr/inventory/service/patientreturn/PatientReturnService.java
  • src/main/java/com/iemr/inventory/service/patientreturn/PatientReturnServiceImpl.java
  • src/main/java/com/iemr/inventory/service/stockEntry/StockEntryServiceImpl.java
  • src/main/java/com/iemr/inventory/service/stockExit/StockExitService.java
  • src/main/java/com/iemr/inventory/service/stockExit/StockExitServiceImpl.java
  • src/main/java/com/iemr/inventory/service/stockadjustment/StockAdjustmentServiceImpl.java
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@sonarqubecloud
Copy link
Copy Markdown

sonarqubecloud Bot commented May 7, 2026

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant