Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

AccountResource.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  1. <?php
  2. namespace App\Filament\Company\Resources\Banking;
  3. use App\Actions\OptionAction\CreateCurrency;
  4. use App\Enums\AccountType;
  5. use App\Facades\Forex;
  6. use App\Filament\Company\Resources\Banking\AccountResource\Pages;
  7. use App\Models\Banking\Account;
  8. use App\Utilities\Currency\CurrencyAccessor;
  9. use App\Utilities\Currency\CurrencyConverter;
  10. use Filament\Facades\Filament;
  11. use Filament\Forms;
  12. use Filament\Forms\Form;
  13. use Filament\Notifications\Notification;
  14. use Filament\Resources\Resource;
  15. use Filament\Support\Enums\FontWeight;
  16. use Filament\Tables;
  17. use Filament\Tables\Table;
  18. use Illuminate\Support\Facades\Auth;
  19. use Illuminate\Support\Facades\DB;
  20. use Illuminate\Validation\Rules\Unique;
  21. use Wallo\FilamentSelectify\Components\ToggleButton;
  22. class AccountResource extends Resource
  23. {
  24. protected static ?string $model = Account::class;
  25. protected static ?string $modelLabel = 'Account';
  26. protected static ?string $navigationIcon = 'heroicon-o-credit-card';
  27. protected static ?string $navigationGroup = 'Banking';
  28. public static function getModelLabel(): string
  29. {
  30. $modelLabel = static::$modelLabel;
  31. return translate($modelLabel);
  32. }
  33. public static function getNavigationParentItem(): ?string
  34. {
  35. if (Filament::hasTopNavigation()) {
  36. return translate(static::$navigationGroup);
  37. }
  38. return null;
  39. }
  40. public static function form(Form $form): Form
  41. {
  42. return $form
  43. ->schema([
  44. Forms\Components\Group::make()
  45. ->schema([
  46. Forms\Components\Section::make('Account Information')
  47. ->schema([
  48. Forms\Components\Select::make('type')
  49. ->options(AccountType::class)
  50. ->localizeLabel()
  51. ->searchable()
  52. ->default('checking')
  53. ->live()
  54. ->required(),
  55. Forms\Components\TextInput::make('name')
  56. ->maxLength(100)
  57. ->localizeLabel()
  58. ->required(),
  59. Forms\Components\TextInput::make('number')
  60. ->localizeLabel('Account Number')
  61. ->unique(ignoreRecord: true, modifyRuleUsing: static function (Unique $rule, $state) {
  62. $companyId = Auth::user()->currentCompany->id;
  63. return $rule->where('company_id', $companyId)->where('number', $state);
  64. })
  65. ->maxLength(20)
  66. ->validationAttribute('account number')
  67. ->required(),
  68. ToggleButton::make('enabled')
  69. ->localizeLabel('Default')
  70. ->onLabel(translate('Yes'))
  71. ->offLabel(translate('No'))
  72. ->hidden(static fn (Forms\Get $get) => $get('type') === 'credit_card'),
  73. ])->columns(),
  74. Forms\Components\Section::make('Currency & Balance')
  75. ->schema([
  76. Forms\Components\Select::make('currency_code')
  77. ->localizeLabel('Currency')
  78. ->relationship('currency', 'name')
  79. ->default(CurrencyAccessor::getDefaultCurrency())
  80. ->saveRelationshipsUsing(null)
  81. ->disabledOn('edit')
  82. ->dehydrated()
  83. ->preload()
  84. ->searchable()
  85. ->live()
  86. ->afterStateUpdated(static function (Forms\Set $set, $state, $old, Forms\Get $get) {
  87. $opening_balance = CurrencyConverter::convertAndSet($state, $old, $get('opening_balance'));
  88. if ($opening_balance !== null) {
  89. $set('opening_balance', $opening_balance);
  90. }
  91. })
  92. ->required()
  93. ->createOptionForm([
  94. Forms\Components\Select::make('currency.code')
  95. ->localizeLabel()
  96. ->searchable()
  97. ->options(CurrencyAccessor::getAvailableCurrencies())
  98. ->live()
  99. ->afterStateUpdated(static function (callable $set, $state) {
  100. if ($state === null) {
  101. return;
  102. }
  103. $currency_code = currency($state);
  104. $defaultCurrencyCode = currency()->getCurrency();
  105. $forexEnabled = Forex::isEnabled();
  106. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  107. $set('currency.name', $currency_code->getName() ?? '');
  108. if ($forexEnabled && $exchangeRate !== null) {
  109. $set('currency.rate', $exchangeRate);
  110. }
  111. })
  112. ->required(),
  113. Forms\Components\TextInput::make('currency.name')
  114. ->localizeLabel()
  115. ->maxLength(100)
  116. ->required(),
  117. Forms\Components\TextInput::make('currency.rate')
  118. ->localizeLabel()
  119. ->numeric()
  120. ->required(),
  121. ])->createOptionAction(static function (Forms\Components\Actions\Action $action) {
  122. return $action
  123. ->label('Add Currency')
  124. ->slideOver()
  125. ->modalWidth('md')
  126. ->action(static function (array $data) {
  127. return DB::transaction(static function () use ($data) {
  128. $code = $data['currency']['code'];
  129. $name = $data['currency']['name'];
  130. $rate = $data['currency']['rate'];
  131. return (new CreateCurrency())->create($code, $name, $rate);
  132. });
  133. });
  134. }),
  135. Forms\Components\TextInput::make('opening_balance')
  136. ->required()
  137. ->localizeLabel()
  138. ->disabledOn('edit')
  139. ->dehydrated()
  140. ->money(static fn (Forms\Get $get) => $get('currency_code')),
  141. ])->columns(),
  142. Forms\Components\Tabs::make('Account Specifications')
  143. ->tabs([
  144. Forms\Components\Tabs\Tab::make('Bank Information')
  145. ->icon('heroicon-o-credit-card')
  146. ->schema([
  147. Forms\Components\TextInput::make('bank_name')
  148. ->localizeLabel()
  149. ->maxLength(100),
  150. Forms\Components\TextInput::make('bank_phone')
  151. ->tel()
  152. ->localizeLabel()
  153. ->maxLength(20),
  154. Forms\Components\Textarea::make('bank_address')
  155. ->localizeLabel()
  156. ->columnSpanFull(),
  157. ])->columns(),
  158. Forms\Components\Tabs\Tab::make('Additional Information')
  159. ->icon('heroicon-o-information-circle')
  160. ->schema([
  161. Forms\Components\TextInput::make('description')
  162. ->localizeLabel()
  163. ->maxLength(100),
  164. Forms\Components\SpatieTagsInput::make('tags')
  165. ->localizeLabel()
  166. ->placeholder('Enter tags...')
  167. ->type('statuses')
  168. ->suggestions([
  169. 'Business',
  170. 'Personal',
  171. 'College Fund',
  172. ]),
  173. Forms\Components\MarkdownEditor::make('notes')
  174. ->columnSpanFull(),
  175. ])->columns(),
  176. ]),
  177. ])->columnSpan(['lg' => 2]),
  178. Forms\Components\Group::make()
  179. ->schema([
  180. Forms\Components\Section::make('Routing Information')
  181. ->schema([
  182. Forms\Components\TextInput::make('aba_routing_number')
  183. ->localizeLabel('ABA Number')
  184. ->integer()
  185. ->length(9),
  186. Forms\Components\TextInput::make('ach_routing_number')
  187. ->localizeLabel('ACH Number')
  188. ->integer()
  189. ->length(9),
  190. ]),
  191. Forms\Components\Section::make('International Bank Information')
  192. ->schema([
  193. Forms\Components\TextInput::make('bic_swift_code')
  194. ->localizeLabel('BIC/SWIFT Code')
  195. ->maxLength(11),
  196. Forms\Components\TextInput::make('iban')
  197. ->localizeLabel('IBAN')
  198. ->maxLength(34),
  199. ]),
  200. ])->columnSpan(['lg' => 1]),
  201. ])->columns(3);
  202. }
  203. public static function table(Table $table): Table
  204. {
  205. return $table
  206. ->columns([
  207. Tables\Columns\TextColumn::make('name')
  208. ->localizeLabel('Account')
  209. ->searchable()
  210. ->weight(FontWeight::Medium)
  211. ->icon(static fn (Account $record) => $record->isEnabled() ? 'heroicon-o-lock-closed' : null)
  212. ->tooltip(static fn (Account $record) => $record->isEnabled() ? 'Default Account' : null)
  213. ->iconPosition('after')
  214. ->description(static fn (Account $record) => $record->number ?: 'N/A')
  215. ->sortable(),
  216. Tables\Columns\TextColumn::make('bank_name')
  217. ->localizeLabel('Bank')
  218. ->placeholder('N/A')
  219. ->description(static fn (Account $record) => $record->bank_phone ?: 'N/A')
  220. ->searchable()
  221. ->sortable(),
  222. Tables\Columns\TextColumn::make('status')
  223. ->badge()
  224. ->localizeLabel()
  225. ->sortable(),
  226. Tables\Columns\TextColumn::make('balance')
  227. ->localizeLabel('Current Balance')
  228. ->sortable()
  229. ->currency(static fn (Account $record) => $record->currency_code, true),
  230. ])
  231. ->filters([
  232. //
  233. ])
  234. ->actions([
  235. Tables\Actions\EditAction::make(),
  236. Tables\Actions\Action::make('update_balance')
  237. ->hidden(function (Account $record) {
  238. $usesDefaultCurrency = $record->currency->isEnabled();
  239. $forexDisabled = Forex::isDisabled();
  240. $sameExchangeRate = $record->currency->rate === $record->currency->live_rate;
  241. return $usesDefaultCurrency || $forexDisabled || $sameExchangeRate;
  242. })
  243. ->label('Update Balance')
  244. ->icon('heroicon-o-currency-dollar')
  245. ->requiresConfirmation()
  246. ->modalDescription('Are you sure you want to update the balance with the latest exchange rate?')
  247. ->before(static function (Tables\Actions\Action $action, Account $record) {
  248. if ($record->currency->isDisabled()) {
  249. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  250. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrency, $record->currency_code);
  251. if ($exchangeRate === null) {
  252. Notification::make()
  253. ->warning()
  254. ->title(__('Exchange Rate Unavailable'))
  255. ->body(__('The exchange rate for this account is currently unavailable. Please try again later.'))
  256. ->persistent()
  257. ->send();
  258. $action->cancel();
  259. }
  260. }
  261. })
  262. ->action(static function (Account $record) {
  263. if ($record->currency->isDisabled()) {
  264. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  265. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrency, $record->currency_code);
  266. $oldExchangeRate = $record->currency->rate;
  267. if ($exchangeRate !== null && $exchangeRate !== $oldExchangeRate) {
  268. $scale = 10 ** $record->currency->precision;
  269. $cleanedBalance = (int) filter_var($record->opening_balance, FILTER_SANITIZE_NUMBER_INT);
  270. $newBalance = ($exchangeRate / $oldExchangeRate) * $cleanedBalance;
  271. $newBalanceInt = (int) round($newBalance, $scale);
  272. $record->opening_balance = money($newBalanceInt, $record->currency_code)->getValue();
  273. $record->currency->rate = $exchangeRate;
  274. $record->currency->save();
  275. $record->save();
  276. Notification::make()
  277. ->success()
  278. ->title('Balance Updated Successfully')
  279. ->body(__('The :name account balance has been updated to reflect the current exchange rate.', ['name' => $record->name]))
  280. ->send();
  281. }
  282. }
  283. }),
  284. ])
  285. ->bulkActions([
  286. Tables\Actions\BulkActionGroup::make([
  287. Tables\Actions\DeleteBulkAction::make(),
  288. ]),
  289. ])
  290. ->checkIfRecordIsSelectableUsing(static fn (Account $record) => $record->isDisabled())
  291. ->emptyStateActions([
  292. Tables\Actions\CreateAction::make(),
  293. ]);
  294. }
  295. public static function getPages(): array
  296. {
  297. return [
  298. 'index' => Pages\ListAccounts::route('/'),
  299. 'create' => Pages\CreateAccount::route('/create'),
  300. 'edit' => Pages\EditAccount::route('/{record}/edit'),
  301. ];
  302. }
  303. }