diff --git a/src/main/java/com/ffii/fpsms/modules/stock/service/StockTakeRecordService.kt b/src/main/java/com/ffii/fpsms/modules/stock/service/StockTakeRecordService.kt index b0bd2f4..abb2f2e 100644 --- a/src/main/java/com/ffii/fpsms/modules/stock/service/StockTakeRecordService.kt +++ b/src/main/java/com/ffii/fpsms/modules/stock/service/StockTakeRecordService.kt @@ -1472,7 +1472,14 @@ private fun applyVarianceAdjustment( } stockOutLineRepository.save(stockOutLine) - val newBalance = (inventory.onHandQty ?: BigDecimal.ZERO).toDouble() - absVariance.toDouble() + // 與 StockOutLineService.createStockLedgerForStockOut 一致:依上一筆 ledger balance 扣減, + // 避免同一批多筆盤虧時每筆都用同一個 inventory.onHandQty 導致 balance 錯誤。 + val itemIdForLedger = inventoryLot.item?.id + ?: throw IllegalArgumentException("Item ID not found for stock take ledger") + val latestLedger = stockLedgerRepository.findLatestByItemId(itemIdForLedger).firstOrNull() + val previousBalance = latestLedger?.balance + ?: (inventory.onHandQty ?: BigDecimal.ZERO).toDouble() + val newBalance = previousBalance - absVariance.toDouble() val stockLedger = StockLedger().apply { this.inventory = inventory this.itemId = inventoryLot.item?.id @@ -1485,7 +1492,7 @@ private fun applyVarianceAdjustment( this.uomId = inventoryLotLine.stockUom?.uom?.id ?: inventory.uom?.id this.date = LocalDate.now() } - stockLedgerRepository.save(stockLedger) + stockLedgerRepository.saveAndFlush(stockLedger) val newOutQty = (inventoryLotLine.outQty ?: BigDecimal.ZERO).add(absVariance) val updateRequest = SaveInventoryLotLineRequest( @@ -1553,7 +1560,12 @@ private fun applyVarianceAdjustment( stockInLine.inventoryLotLine = newInventoryLotLine stockInLineRepository.save(stockInLine) - val newBalance = (inventory.onHandQty ?: BigDecimal.ZERO).toDouble() + plusQty.toDouble() + val itemIdForLedger = newInventoryLot.item?.id + ?: throw IllegalArgumentException("Item ID not found for stock take ledger (in)") + val latestLedger = stockLedgerRepository.findLatestByItemId(itemIdForLedger).firstOrNull() + val previousBalance = latestLedger?.balance + ?: (inventory.onHandQty ?: BigDecimal.ZERO).toDouble() + val newBalance = previousBalance + plusQty.toDouble() val stockLedger = StockLedger().apply { this.inventory = inventory this.itemId = newInventoryLot.item?.id @@ -1566,7 +1578,7 @@ private fun applyVarianceAdjustment( this.uomId = inventoryLotLine.stockUom?.uom?.id ?: inventory.uom?.id this.date = LocalDate.now() } - stockLedgerRepository.save(stockLedger) + stockLedgerRepository.saveAndFlush(stockLedger) } } open fun updateStockTakeRecordStatusToNotMatch(stockTakeRecordId: Long): StockTakeRecord {