57 lines
1.9 KiB
PHP
57 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Observers;
|
|
|
|
use App\Models\EggCollection;
|
|
use App\Models\WarehouseStock;
|
|
|
|
class EggCollectionObserver
|
|
{
|
|
/**
|
|
* Handle the EggCollection "updated" event.
|
|
*/
|
|
public function updated(EggCollection $eggCollection): void
|
|
{
|
|
if ($eggCollection->isDirty('warehouse_id')) {
|
|
$oldWarehouseId = $eggCollection->getOriginal('warehouse_id');
|
|
$newWarehouseId = $eggCollection->warehouse_id;
|
|
|
|
foreach ($eggCollection->items as $item) {
|
|
if ($oldWarehouseId) {
|
|
WarehouseStock::adjustStock($oldWarehouseId, $item->unit_id, $item->is_broken, -$item->quantity);
|
|
}
|
|
if ($newWarehouseId) {
|
|
WarehouseStock::adjustStock($newWarehouseId, $item->unit_id, $item->is_broken, $item->quantity);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle the EggCollection "deleted" event.
|
|
*/
|
|
public function deleted(EggCollection $eggCollection): void
|
|
{
|
|
// Items are usually deleted via cascade or manual deletion which triggers ItemObserver.
|
|
// But if it's a soft delete, we should decide if we want to remove stock.
|
|
// Assuming we want to remove stock when production record is deleted.
|
|
if (! $eggCollection->isForceDeleting() && $warehouseId = $eggCollection->warehouse_id) {
|
|
foreach ($eggCollection->items as $item) {
|
|
WarehouseStock::adjustStock($warehouseId, $item->unit_id, $item->is_broken, -$item->quantity);
|
|
}
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Handle the EggCollection "restored" event.
|
|
*/
|
|
public function restored(EggCollection $eggCollection): void
|
|
{
|
|
if ($warehouseId = $eggCollection->warehouse_id) {
|
|
foreach ($eggCollection->items as $item) {
|
|
WarehouseStock::adjustStock($warehouseId, $item->unit_id, $item->is_broken, $item->quantity);
|
|
}
|
|
}
|
|
}
|
|
}
|