Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

CurrencyResource.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260
  1. <?php
  2. namespace App\Filament\Company\Resources\Setting;
  3. use App\Facades\Forex;
  4. use App\Filament\Company\Resources\Setting\CurrencyResource\Pages;
  5. use App\Models\Banking\Account;
  6. use App\Models\Setting\Currency;
  7. use App\Models\Setting\Currency as CurrencyModel;
  8. use App\Traits\ChecksForeignKeyConstraints;
  9. use App\Traits\NotifiesOnDelete;
  10. use App\Utilities\Currency\CurrencyAccessor;
  11. use Closure;
  12. use Filament\Facades\Filament;
  13. use Filament\Forms;
  14. use Filament\Forms\Form;
  15. use Filament\Resources\Resource;
  16. use Filament\Support\Enums\FontWeight;
  17. use Filament\Tables;
  18. use Filament\Tables\Table;
  19. use Illuminate\Database\Eloquent\Collection;
  20. use Wallo\FilamentSelectify\Components\ToggleButton;
  21. class CurrencyResource extends Resource
  22. {
  23. use ChecksForeignKeyConstraints;
  24. use NotifiesOnDelete;
  25. protected static ?string $model = CurrencyModel::class;
  26. protected static ?string $modelLabel = 'Currency';
  27. protected static ?string $navigationIcon = 'heroicon-o-currency-dollar';
  28. protected static ?string $navigationGroup = 'Settings';
  29. protected static ?string $slug = 'settings/currencies';
  30. public static function getModelLabel(): string
  31. {
  32. $modelLabel = static::$modelLabel;
  33. return translate($modelLabel);
  34. }
  35. public static function getNavigationParentItem(): ?string
  36. {
  37. if (Filament::hasTopNavigation()) {
  38. return translate('Finance');
  39. }
  40. return null;
  41. }
  42. public static function form(Form $form): Form
  43. {
  44. return $form
  45. ->schema([
  46. Forms\Components\Section::make('General')
  47. ->schema([
  48. Forms\Components\Select::make('code')
  49. ->options(CurrencyAccessor::getAvailableCurrencies())
  50. ->searchable()
  51. ->live()
  52. ->required()
  53. ->localizeLabel()
  54. ->hidden(static fn (Forms\Get $get, $state): bool => $get('enabled') && $state !== null)
  55. ->afterStateUpdated(static function (Forms\Set $set, $state) {
  56. $fields = ['name', 'precision', 'symbol', 'symbol_first', 'decimal_mark', 'thousands_separator'];
  57. if ($state === null) {
  58. array_walk($fields, static fn ($field) => $set($field, null));
  59. return;
  60. }
  61. $currencyDetails = CurrencyAccessor::getAllCurrencies()[$state] ?? [];
  62. $defaultCurrencyCode = CurrencyAccessor::getDefaultCurrency();
  63. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrencyCode, $state);
  64. if ($exchangeRate !== null) {
  65. $set('rate', $exchangeRate);
  66. }
  67. array_walk($fields, static fn ($field) => $set($field, $currencyDetails[$field] ?? null));
  68. }),
  69. Forms\Components\TextInput::make('code')
  70. ->localizeLabel()
  71. ->hidden(static fn (Forms\Get $get): bool => ! ($get('enabled') && $get('code') !== null))
  72. ->disabled(static fn (Forms\Get $get): bool => $get('enabled'))
  73. ->dehydrated()
  74. ->required(),
  75. Forms\Components\TextInput::make('name')
  76. ->localizeLabel()
  77. ->maxLength(50)
  78. ->required(),
  79. Forms\Components\TextInput::make('rate')
  80. ->numeric()
  81. ->rule('gt:0')
  82. ->live()
  83. ->localizeLabel()
  84. ->disabled(static fn (?CurrencyModel $record): bool => $record?->isEnabled() ?? false)
  85. ->dehydrated()
  86. ->required(),
  87. Forms\Components\Select::make('precision')
  88. ->localizeLabel()
  89. ->options(['0', '1', '2', '3', '4'])
  90. ->required(),
  91. Forms\Components\TextInput::make('symbol')
  92. ->localizeLabel()
  93. ->maxLength(5)
  94. ->required(),
  95. Forms\Components\Select::make('symbol_first')
  96. ->localizeLabel('Symbol Position')
  97. ->boolean(translate('Before Amount'), translate('After Amount'), translate('Select a symbol position'))
  98. ->required(),
  99. Forms\Components\TextInput::make('decimal_mark')
  100. ->localizeLabel('Decimal Separator')
  101. ->maxLength(1)
  102. ->rule(static function (Forms\Get $get): Closure {
  103. return static function ($attribute, $value, Closure $fail) use ($get) {
  104. if ($value === $get('thousands_separator')) {
  105. $fail(translate('Separators must be unique.'));
  106. }
  107. };
  108. })
  109. ->required(),
  110. Forms\Components\TextInput::make('thousands_separator')
  111. ->localizeLabel()
  112. ->maxLength(1)
  113. ->rule(static function (Forms\Get $get): Closure {
  114. return static function ($attribute, $value, Closure $fail) use ($get) {
  115. if ($value === $get('decimal_mark')) {
  116. $fail(translate('Separators must be unique.'));
  117. }
  118. };
  119. })
  120. ->nullable(),
  121. ToggleButton::make('enabled')
  122. ->localizeLabel('Default')
  123. ->onLabel(CurrencyModel::enabledLabel())
  124. ->offLabel(CurrencyModel::disabledLabel())
  125. ->disabled(static fn (?CurrencyModel $record): bool => $record?->isEnabled() ?? false)
  126. ->dehydrated()
  127. ->live()
  128. ->afterStateUpdated(static function (Forms\Set $set, Forms\Get $get, $state) {
  129. $enabledState = (bool) $state;
  130. $code = $get('code');
  131. if (! $code) {
  132. return;
  133. }
  134. if ($enabledState) {
  135. $set('rate', 1);
  136. return;
  137. }
  138. $forexEnabled = Forex::isEnabled();
  139. if ($forexEnabled) {
  140. $defaultCurrencyCode = CurrencyAccessor::getDefaultCurrency();
  141. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrencyCode, $code);
  142. if ($exchangeRate !== null) {
  143. $set('rate', $exchangeRate);
  144. }
  145. }
  146. }),
  147. ])->columns(),
  148. ]);
  149. }
  150. public static function table(Table $table): Table
  151. {
  152. return $table
  153. ->columns([
  154. Tables\Columns\TextColumn::make('name')
  155. ->localizeLabel()
  156. ->weight(FontWeight::Medium)
  157. ->icon(static fn (CurrencyModel $record) => $record->isEnabled() ? 'heroicon-o-lock-closed' : null)
  158. ->tooltip(static function (CurrencyModel $record) {
  159. $tooltipMessage = translate('Default :Record', [
  160. 'Record' => static::getModelLabel(),
  161. ]);
  162. return $record->isEnabled() ? $tooltipMessage : null;
  163. })
  164. ->iconPosition('after')
  165. ->searchable()
  166. ->sortable(),
  167. Tables\Columns\TextColumn::make('code')
  168. ->localizeLabel()
  169. ->searchable()
  170. ->sortable(),
  171. Tables\Columns\TextColumn::make('symbol')
  172. ->localizeLabel()
  173. ->searchable()
  174. ->sortable(),
  175. Tables\Columns\TextColumn::make('rate')
  176. ->localizeLabel()
  177. ->searchable()
  178. ->sortable(),
  179. ])
  180. ->filters([
  181. //
  182. ])
  183. ->actions([
  184. Tables\Actions\EditAction::make(),
  185. Tables\Actions\DeleteAction::make()
  186. ->before(function (Tables\Actions\DeleteAction $action, Currency $record) {
  187. $modelsToCheck = [
  188. Account::class,
  189. ];
  190. $isUsed = self::isForeignKeyUsed('currency_code', $record->code, $modelsToCheck);
  191. if ($isUsed) {
  192. $reason = 'in use';
  193. self::notifyBeforeDelete($record, $reason);
  194. $action->cancel();
  195. }
  196. }),
  197. ])
  198. ->bulkActions([
  199. Tables\Actions\BulkActionGroup::make([
  200. Tables\Actions\DeleteBulkAction::make()
  201. ->before(static function (Tables\Actions\DeleteBulkAction $action, Collection $records) {
  202. foreach ($records as $record) {
  203. $modelsToCheck = [
  204. Account::class,
  205. ];
  206. $isUsed = self::isForeignKeyUsed('currency_code', $record->code, $modelsToCheck);
  207. if ($isUsed) {
  208. $reason = 'in use';
  209. self::notifyBeforeDelete($record, $reason);
  210. $action->cancel();
  211. }
  212. }
  213. }),
  214. ]),
  215. ])
  216. ->checkIfRecordIsSelectableUsing(static function (CurrencyModel $record) {
  217. return $record->isDisabled();
  218. })
  219. ->emptyStateActions([
  220. Tables\Actions\CreateAction::make(),
  221. ]);
  222. }
  223. public static function getPages(): array
  224. {
  225. return [
  226. 'index' => Pages\ListCurrencies::route('/'),
  227. 'create' => Pages\CreateCurrency::route('/create'),
  228. 'edit' => Pages\EditCurrency::route('/{record}/edit'),
  229. ];
  230. }
  231. }