File: /var/www/ipsremont-demo/app/Models/Currency.php
<?php
namespace App\Models;
use App\Helpers\UserHelper;
use App\Traits\Displayed;
use App\Traits\My;
use App\Traits\Sortable;
use DateTime;
use Illuminate\Database\Eloquent\SoftDeletes;
/**
* @property int $id
* @property string $name
* @property string $code
* @property ?string $short_name
* @property ?string $full_name
* @property ?string $subunit_full_name
* @property ?string $symbol
* @property double $rate
* @property string $deleted_at
* @property string $created_at
* @property string $updated_at
*/
class Currency extends BaseModel
{
use SoftDeletes;
use Sortable;
use Displayed;
use My;
public const DEFAULT_CURRENCY_SYMBOL = '₽';
public const DEFAULT_CURRENCY_SHORT = 'руб';
protected $table = 'currencies';
protected $fillable = [
'name',
'code',
'short_name',
'full_name',
'subunit_full_name',
'symbol',
'rate',
];
protected static $labels = [
'name' => 'currencies.name',
'code' => 'currencies.code',
'short_name' => 'currencies.short_name',
'full_name' => 'currencies.full_name',
'subunit_full_name' => 'currencies.subunit_full_name',
'symbol' => 'currencies.symbol',
'rate' => 'currencies.rate',
];
public static function columns(): array
{
return [
'fields' => [
[
'displayName' => 'currencies.name',
'field' => 'name',
'sort' => true,
'sortType' => 'asc',
],
[
'displayName' => 'currencies.code',
'field' => 'code',
'sort' => true,
'sortType' => 'asc',
'class' => 'w-400px',
],
[
'displayName' => 'currencies.rate',
'field' => 'rate',
'sort' => true,
'sortType' => 'asc',
'class' => 'w-400px',
],
],
'sortDefault' => [
[
'field' => 'id',
'sort' => 'desc',
],
],
];
}
public function getRate(DateTime $date = null): string
{
if (empty($date)) {
return $this->rate;
}
// Может быть случай что нет исторической расценки и тогда будет считаться по текущей
// в реальной жизни такого вряд ли может быть
/** @var CurrencyRateHistory $historyRecord */
$historyRecord = CurrencyRateHistory::query()
->where('currency_id', $this->id)
->where('created_at', '<=', $date)
->orderBy('id', 'desc')
->first();
if (empty($historyRecord->rate)) {
return $this->rate;
}
return $historyRecord->rate;
}
public static function convertToRubles(float $price): float
{
$currencyRate = UserHelper::getUser()->branch->region->currency->rate ?? 1;
return round($price / $currencyRate, 2);
}
public static function convertToRegion(float $price): float
{
$currencyRate = UserHelper::getUser()->branch->region->currency->rate ?? 1;
return round($price * $currencyRate, 2);
}
}