diff --git a/app/Livewire/Studio/Manage/Purchase/Index.php b/app/Livewire/Studio/Manage/Purchase/Index.php index d916470..324f87c 100644 --- a/app/Livewire/Studio/Manage/Purchase/Index.php +++ b/app/Livewire/Studio/Manage/Purchase/Index.php @@ -3,6 +3,7 @@ namespace App\Livewire\Studio\Manage\Purchase; use App\Models\Purchase; +use App\Traits\Purchase\WithUpdateStock; use App\Traits\WithCloseModal; use App\Traits\WithConfirmation; use App\Traits\WithToast; @@ -13,10 +14,14 @@ #[Title('Belanja')] class Index extends Component { - use WithCloseModal, WithConfirmation, WithToast; + use WithCloseModal, WithConfirmation, WithToast, WithUpdateStock; public function delete(Purchase $purchase) { + foreach ($purchase->items as $item) { + $this->decreaseOutletStock($purchase->outlet, $item); + } + $purchase->delete(); $this->dispatch('refreshDatatable'); diff --git a/app/Traits/Purchase/WithUpdateStock.php b/app/Traits/Purchase/WithUpdateStock.php index e357e86..b71b644 100644 --- a/app/Traits/Purchase/WithUpdateStock.php +++ b/app/Traits/Purchase/WithUpdateStock.php @@ -26,9 +26,7 @@ public function increaseOutletStock($outlet, $item) return; } - $existing = $outlet->{$relation}() - ->where("{$relation}.id", $item->purchasable_id) - ->first(); + $existing = $outlet->{$relation}()->where("{$relation}.id", $item->purchasable_id)->first(); if ($existing) { $currentStock = $existing->pivot->stock ?? 0; @@ -41,4 +39,33 @@ public function increaseOutletStock($outlet, $item) ]); } } + + public function decreaseOutletStock($outlet, $item) + { + $quantity = $item->quantity; + + switch ($item->purchasable_type) { + case Perfume::class: + $relation = 'perfumes'; + break; + case Product::class: + $relation = 'products'; + break; + case Bottle::class: + $relation = 'bottles'; + break; + default: + return; + } + + $existing = $outlet->{$relation}()->where("{$relation}.id", $item->purchasable_id)->first(); + + if ($existing) { + $currentStock = $existing->pivot->stock ?? 0; + $newStock = max(0, $currentStock - $quantity); + $outlet->{$relation}()->updateExistingPivot($item->purchasable_id, [ + 'stock' => $newStock, + ]); + } + } }