incr/app/Models/Transactions/Entry.php

53 lines
1.2 KiB
PHP

<?php
declare(strict_types=1);
namespace App\Models\Transactions;
use App\Models\Tracker;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
class Entry extends Model
{
protected $fillable = [
'tracker_id',
'date',
'quantity',
'unit_price',
'total_cost',
];
protected function casts(): array
{
return [
'date' => 'date',
'quantity' => 'decimal:6',
'unit_price' => 'decimal:4',
'total_cost' => 'decimal:2',
];
}
public function tracker(): BelongsTo
{
return $this->belongsTo(Tracker::class);
}
public static function totalQuantity(int $trackerId): float
{
return (float) static::where('tracker_id', $trackerId)->sum('quantity');
}
public static function totalCost(int $trackerId): float
{
return (float) static::where('tracker_id', $trackerId)->sum('total_cost');
}
public static function averageCostPerUnit(int $trackerId): float
{
$totalQuantity = static::totalQuantity($trackerId);
$totalCost = static::totalCost($trackerId);
return $totalQuantity > 0 ? $totalCost / $totalQuantity : 0;
}
}