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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  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\Services\AccountService;
  11. use App\Utilities\Currency\CurrencyAccessor;
  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. 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(static::$navigationGroup);
  39. }
  40. return null;
  41. }
  42. public static function form(Form $form): Form
  43. {
  44. return $form
  45. ->schema([
  46. Forms\Components\Section::make('Account Information')
  47. ->schema([
  48. Forms\Components\Select::make('type')
  49. ->options(BankAccountType::class)
  50. ->localizeLabel()
  51. ->searchable()
  52. ->columnSpan(1)
  53. ->default(BankAccountType::DEFAULT)
  54. ->live()
  55. ->afterStateUpdated(static function (Forms\Set $set, $state, ?BankAccount $record, string $operation) {
  56. if ($operation === 'create') {
  57. $set('account.subtype_id', null);
  58. } elseif ($operation === 'edit' && $record !== null) {
  59. if ($state !== $record->type->value) {
  60. $set('account.subtype_id', null);
  61. } else {
  62. $set('account.subtype_id', $record->account->subtype_id);
  63. }
  64. }
  65. })
  66. ->required(),
  67. Forms\Components\Group::make()
  68. ->columnStart(2)
  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. ->columns(2)
  85. ->columnSpanFull()
  86. ->schema([
  87. Forms\Components\TextInput::make('name')
  88. ->maxLength(100)
  89. ->localizeLabel()
  90. ->required(),
  91. Forms\Components\Select::make('currency_code')
  92. ->localizeLabel('Currency')
  93. ->relationship('currency', 'name')
  94. ->default(CurrencyAccessor::getDefaultCurrency())
  95. ->preload()
  96. ->searchable()
  97. ->live()
  98. ->required()
  99. ->createOptionForm([
  100. Forms\Components\Select::make('code')
  101. ->localizeLabel()
  102. ->searchable()
  103. ->options(CurrencyAccessor::getAvailableCurrencies())
  104. ->live()
  105. ->afterStateUpdated(static function (callable $set, $state) {
  106. if ($state === null) {
  107. return;
  108. }
  109. $currency_code = currency($state);
  110. $defaultCurrencyCode = currency()->getCurrency();
  111. $forexEnabled = Forex::isEnabled();
  112. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  113. $set('name', $currency_code->getName() ?? '');
  114. if ($forexEnabled && $exchangeRate !== null) {
  115. $set('rate', $exchangeRate);
  116. }
  117. })
  118. ->required(),
  119. Forms\Components\TextInput::make('name')
  120. ->localizeLabel()
  121. ->maxLength(100)
  122. ->required(),
  123. Forms\Components\TextInput::make('rate')
  124. ->localizeLabel()
  125. ->numeric()
  126. ->required(),
  127. ])->createOptionAction(static function (Forms\Components\Actions\Action $action) {
  128. return $action
  129. ->label('Add Currency')
  130. ->slideOver()
  131. ->modalWidth('md')
  132. ->action(static function (array $data) {
  133. return DB::transaction(static function () use ($data) {
  134. $code = $data['code'];
  135. $name = $data['name'];
  136. $rate = $data['rate'];
  137. return (new CreateCurrency())->create($code, $name, $rate);
  138. });
  139. });
  140. }),
  141. ]),
  142. Forms\Components\Group::make()
  143. ->columns(2)
  144. ->columnSpanFull()
  145. ->schema([
  146. Forms\Components\TextInput::make('number')
  147. ->localizeLabel('Account Number')
  148. ->unique(ignoreRecord: true, modifyRuleUsing: static function (Unique $rule, $state) {
  149. $companyId = Auth::user()->currentCompany->id;
  150. return $rule->where('company_id', $companyId)->where('number', $state);
  151. })
  152. ->maxLength(20)
  153. ->validationAttribute('account number')
  154. ->required(),
  155. ToggleButton::make('enabled')
  156. ->localizeLabel('Default'),
  157. ]),
  158. ])->columns(),
  159. ]);
  160. }
  161. public static function table(Table $table): Table
  162. {
  163. return $table
  164. ->columns([
  165. Tables\Columns\TextColumn::make('account.name')
  166. ->localizeLabel('Account')
  167. ->searchable()
  168. ->weight(FontWeight::Medium)
  169. ->icon(static fn (BankAccount $record) => $record->isEnabled() ? 'heroicon-o-lock-closed' : null)
  170. ->tooltip(static fn (BankAccount $record) => $record->isEnabled() ? 'Default Account' : null)
  171. ->iconPosition('after')
  172. ->description(static fn (BankAccount $record) => $record->mask ?: 'N/A')
  173. ->sortable(),
  174. Tables\Columns\TextColumn::make('account.code') // Just so I could display the balance in the table for now
  175. ->localizeLabel('Current Balance')
  176. ->sortable()
  177. ->formatStateUsing(function (BankAccount $record) {
  178. $accountService = app(AccountService::class);
  179. $startDate = $record->account->company->locale->fiscalYearStartDate();
  180. $endDate = $record->account->company->locale->fiscalYearEndDate();
  181. return $accountService->getEndingBalance($record->account, $startDate, $endDate)?->formatted();
  182. }),
  183. ])
  184. ->filters([
  185. //
  186. ])
  187. ->actions([
  188. Tables\Actions\EditAction::make(),
  189. Tables\Actions\Action::make('update_balance')
  190. ->hidden(function (BankAccount $record) {
  191. $usesDefaultCurrency = $record->account->currency->isEnabled();
  192. $forexDisabled = Forex::isDisabled();
  193. $sameExchangeRate = $record->account->currency->rate === $record->account->currency->live_rate;
  194. return $usesDefaultCurrency || $forexDisabled || $sameExchangeRate;
  195. })
  196. ->label('Update Balance')
  197. ->icon('heroicon-o-currency-dollar')
  198. ->requiresConfirmation()
  199. ->modalDescription('Are you sure you want to update the balance with the latest exchange rate?')
  200. ->before(static function (Tables\Actions\Action $action, BankAccount $record) {
  201. if ($record->account->currency->isDisabled()) {
  202. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  203. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrency, $record->account->currency_code);
  204. if ($exchangeRate === null) {
  205. Notification::make()
  206. ->warning()
  207. ->title(__('Exchange Rate Unavailable'))
  208. ->body(__('The exchange rate for this account is currently unavailable. Please try again later.'))
  209. ->persistent()
  210. ->send();
  211. $action->cancel();
  212. }
  213. }
  214. })
  215. ->action(static function (BankAccount $record) {
  216. if ($record->account->currency->isDisabled()) {
  217. $defaultCurrency = CurrencyAccessor::getDefaultCurrency();
  218. $exchangeRate = Forex::getCachedExchangeRate($defaultCurrency, $record->account->currency_code);
  219. $oldExchangeRate = $record->account->currency->rate;
  220. if ($exchangeRate !== null && $exchangeRate !== $oldExchangeRate) {
  221. $scale = 10 ** $record->account->currency->precision;
  222. $cleanedBalance = (int) filter_var($record->account->starting_balance, FILTER_SANITIZE_NUMBER_INT);
  223. $newBalance = ($exchangeRate / $oldExchangeRate) * $cleanedBalance;
  224. $newBalanceInt = (int) round($newBalance, $scale);
  225. $record->account->starting_balance = money($newBalanceInt, $record->account->currency_code)->getValue();
  226. $record->account->currency->rate = $exchangeRate;
  227. $record->account->currency->save();
  228. $record->save();
  229. Notification::make()
  230. ->success()
  231. ->title('Balance Updated Successfully')
  232. ->body(__('The :name account balance has been updated to reflect the current exchange rate.', ['name' => $record->account->name]))
  233. ->send();
  234. }
  235. }
  236. }),
  237. ])
  238. ->bulkActions([
  239. Tables\Actions\BulkActionGroup::make([
  240. Tables\Actions\DeleteBulkAction::make(),
  241. ]),
  242. ])
  243. ->emptyStateActions([
  244. Tables\Actions\CreateAction::make(),
  245. ]);
  246. }
  247. public static function getPages(): array
  248. {
  249. return [
  250. 'index' => Pages\ListAccounts::route('/'),
  251. 'create' => Pages\CreateAccount::route('/create'),
  252. 'edit' => Pages\EditAccount::route('/{record}/edit'),
  253. ];
  254. }
  255. public static function groupSubtypesBySubtypeType($typeString): array
  256. {
  257. $category = match ($typeString) {
  258. BankAccountType::Depository->value, BankAccountType::Investment->value => AccountCategory::Asset,
  259. BankAccountType::Credit->value, BankAccountType::Loan->value => AccountCategory::Liability,
  260. default => null,
  261. };
  262. if ($category === null) {
  263. return [];
  264. }
  265. $subtypes = AccountSubtype::where('category', $category)->get();
  266. return $subtypes->groupBy(fn (AccountSubtype $subtype) => $subtype->type->getLabel())
  267. ->map(fn (Collection $subtypes, string $type) => $subtypes->mapWithKeys(static fn (AccountSubtype $subtype) => [$subtype->id => $subtype->name]))
  268. ->toArray();
  269. }
  270. }