layer-chicken/app/Models/WarehouseStock.php

56 lines
1.3 KiB
PHP

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class WarehouseStock extends Model
{
use HasFactory;
protected $guarded = ['id'];
protected $casts = [
'quantity' => 'decimal:2',
];
public function warehouse()
{
return $this->belongsTo(Warehouse::class);
}
public function unit()
{
return $this->belongsTo(Unit::class);
}
public static function adjustStock(int $warehouseId, int $unitId, bool $isBroken, float $quantity): void
{
if ($isBroken) {
return;
}
$stock = self::firstOrCreate([
'warehouse_id' => $warehouseId,
'unit_id' => $unitId,
], [
'quantity' => 0,
]);
$stock->increment('quantity', $quantity);
}
public static function getQuantity(int $warehouseId, int $unitId): float
{
return (float) (self::where('warehouse_id', $warehouseId)
->where('unit_id', $unitId)
->first()?->quantity ?? 0);
}
public static function hasSufficientStock(int $warehouseId, int $unitId, float|int $neededQuantity): bool
{
return self::getQuantity($warehouseId, $unitId) >= $neededQuantity;
}
}