Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

Currency.php 2.3KB

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