incr/app/Models/Pricing/AssetPrice.php
2025-08-01 00:36:05 +02:00

84 lines
2.1 KiB
PHP

<?php
namespace App\Models\Pricing;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Support\Carbon;
/**
* @method static latest(string $string)
* @method static where(string $string, string $string1, string $date)
* @method static updateOrCreate(string[] $array, float[] $array1)
* @method static orderBy(string $string, string $string1)
* @property Carbon $date
* @property float $price
*/
class AssetPrice extends Model
{
use HasFactory;
protected $fillable = [
'asset_id',
'date',
'price',
];
protected $casts = [
'date' => 'date',
'price' => 'decimal:4',
];
public function asset(): BelongsTo
{
return $this->belongsTo(\App\Models\Asset::class);
}
public static function current(int $assetId = null): ?float
{
$query = static::latest('date');
if ($assetId) {
$query->where('asset_id', $assetId);
}
$latestPrice = $query->first();
return $latestPrice ? $latestPrice->price : null;
}
public static function forDate(string $date, int $assetId = null): ?float
{
$query = static::where('date', '<=', $date)
->orderBy('date', 'desc');
if ($assetId) {
$query->where('asset_id', $assetId);
}
$price = $query->first();
return $price ? $price->price : null;
}
public static function updatePrice(int $assetId, string $date, float $price): self
{
return static::updateOrCreate(
['asset_id' => $assetId, 'date' => $date],
['price' => $price]
);
}
public static function history(int $assetId = null, int $limit = 30): Collection
{
$query = static::orderBy('date', 'desc')->limit($limit);
if ($assetId) {
$query->where('asset_id', $assetId);
}
return $query->get();
}
}