fix: Adjust stock opname logic to apply the difference between physical and system quantities to the current stock.

This commit is contained in:
Yoga Pangestu 2026-02-23 22:29:56 +07:00
parent 6af61d9dd3
commit 9d8e264929

View File

@ -74,20 +74,26 @@ public function approveApproval(StockOpname $stockOpname): void
->where($itemable->getTable().'.id', $itemable->id)
->first();
// Current stock is the stock of the item in the outlet at the time the stock opname was created
$currentStock = $currentPivot?->pivot?->stock ?? 0;
$quantity = $item->qty_physical;
// Calculate the difference between the physical stock and the system stock AT THE TIME the stock opname was created
// then apply the difference to the current stock
// Example: qty_system=100, qty_physical=90, transaction 20 occurred
// currentStock=80, difference=-10, newStock=80+(-10)=70 ✓
$difference = $item->qty_physical - $item->qty_system;
$newStock = max(0, $currentStock + $difference);
$outlet->$relationName()->syncWithoutDetaching([
$itemable->id => ['stock' => $quantity],
$itemable->id => ['stock' => $newStock],
]);
StockActivityLogService::stockOpname(
stockOpname: $stockOpname,
product: $itemable,
quantityChange: $quantity - $currentStock,
quantityChange: $newStock - $currentStock,
previousStock: $currentStock,
newStock: $quantity,
newStock: $newStock,
note: $stockOpname->note
);
}