53 lines
1.7 KiB
PHP
53 lines
1.7 KiB
PHP
<?php
|
||
|
||
namespace App\Helper;
|
||
|
||
use Illuminate\Support\Facades\DB;
|
||
use Modules\Restaurant\Models\Ingredient;
|
||
use Modules\Restaurant\Models\IngredientDamage;
|
||
use Modules\Restaurant\Models\Stock;
|
||
|
||
class IngredientDamageHelper
|
||
{
|
||
public static function createDamage(array $data)
|
||
{
|
||
DB::beginTransaction();
|
||
|
||
try {
|
||
// 1️⃣ Create ingredient damage record
|
||
$damage = IngredientDamage::create($data);
|
||
|
||
// 2️⃣ Reduce ingredient stock
|
||
$ingredient = Ingredient::find($data['ingredient_id']);
|
||
if (! $ingredient) {
|
||
throw new \Exception('Ingredient not found.');
|
||
}
|
||
|
||
$ingredient->decrement('stock_quantity', $data['quantity']);
|
||
|
||
// 3️⃣ Log stock movement
|
||
Stock::create([
|
||
'restaurant_id' => $data['restaurant_id'],
|
||
'ingredient_id' => $data['ingredient_id'],
|
||
'type' => 'damage',
|
||
'quantity' => $data['quantity'],
|
||
'unit_cost' => $data['unit_cost'] ?? null,
|
||
'total_cost' => isset($data['unit_cost']) ? $data['unit_cost'] * $data['quantity'] : null,
|
||
'reference_type' => 'IngredientDamage',
|
||
'purchase_id' => $data['purchase_id'],
|
||
'batch_no' => $data['batch_no'] ?? null,
|
||
'expiry_date' => null,
|
||
'added_by' => $data['reported_by'] ?? auth()->id(),
|
||
'remarks' => $data['reason'] ?? 'Ingredient damage',
|
||
]);
|
||
|
||
DB::commit();
|
||
|
||
return $damage;
|
||
} catch (\Exception $e) {
|
||
DB::rollBack();
|
||
throw $e;
|
||
}
|
||
}
|
||
}
|