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 15KB

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