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.

AccountResource.php 17KB

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