You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Currency.php 2.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. namespace App\Models\Setting;
  3. use App\Casts\CurrencyRateCast;
  4. use App\Concerns\Blamable;
  5. use App\Concerns\CompanyOwned;
  6. use App\Concerns\HasDefault;
  7. use App\Concerns\SyncsWithCompanyDefaults;
  8. use App\Facades\Forex;
  9. use App\Models\Accounting\Account;
  10. use App\Models\History\AccountHistory;
  11. use App\Observers\CurrencyObserver;
  12. use App\Utilities\Currency\CurrencyAccessor;
  13. use Database\Factories\Setting\CurrencyFactory;
  14. use Illuminate\Database\Eloquent\Attributes\ObservedBy;
  15. use Illuminate\Database\Eloquent\Casts\Attribute;
  16. use Illuminate\Database\Eloquent\Factories\Factory;
  17. use Illuminate\Database\Eloquent\Factories\HasFactory;
  18. use Illuminate\Database\Eloquent\Model;
  19. use Illuminate\Database\Eloquent\Relations\HasMany;
  20. use Illuminate\Database\Eloquent\Relations\HasOne;
  21. #[ObservedBy(CurrencyObserver::class)]
  22. class Currency extends Model
  23. {
  24. use Blamable;
  25. use CompanyOwned;
  26. use HasDefault;
  27. use HasFactory;
  28. use SyncsWithCompanyDefaults;
  29. protected $table = 'currencies';
  30. protected $fillable = [
  31. 'company_id',
  32. 'name',
  33. 'code',
  34. 'rate',
  35. 'precision',
  36. 'symbol',
  37. 'symbol_first',
  38. 'decimal_mark',
  39. 'thousands_separator',
  40. 'enabled',
  41. 'created_by',
  42. 'updated_by',
  43. ];
  44. protected $casts = [
  45. 'enabled' => 'boolean',
  46. 'symbol_first' => 'boolean',
  47. 'rate' => CurrencyRateCast::class,
  48. ];
  49. protected $appends = ['live_rate'];
  50. protected function liveRate(): Attribute
  51. {
  52. return Attribute::get(static function (mixed $value, array $attributes): ?float {
  53. $baseCurrency = CurrencyAccessor::getDefaultCurrency();
  54. $targetCurrency = $attributes['code'];
  55. if ($baseCurrency === $targetCurrency) {
  56. return 1;
  57. }
  58. $exchangeRate = Forex::getCachedExchangeRate($baseCurrency, $targetCurrency);
  59. return $exchangeRate ?? null;
  60. });
  61. }
  62. public function defaultCurrency(): HasOne
  63. {
  64. return $this->hasOne(CompanyDefault::class, 'currency_code', 'code');
  65. }
  66. public function accounts(): HasMany
  67. {
  68. return $this->hasMany(Account::class, 'currency_code', 'code');
  69. }
  70. public function accountHistories(): HasMany
  71. {
  72. return $this->hasMany(AccountHistory::class, 'currency_code', 'code');
  73. }
  74. protected static function newFactory(): Factory
  75. {
  76. return CurrencyFactory::new();
  77. }
  78. }