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\Services\AccountService;
  11. use App\Utilities\Currency\CurrencyAccessor;
  12. use App\Utilities\Currency\CurrencyConverter;
  13. use BackedEnum;
  14. use Filament\Facades\Filament;
  15. use Filament\Forms;
  16. use Filament\Forms\Form;
  17. use Filament\Notifications\Notification;
  18. use Filament\Resources\Resource;
  19. use Filament\Support\Enums\FontWeight;
  20. use Filament\Tables;
  21. use Filament\Tables\Table;
  22. use Illuminate\Support\Collection;
  23. use Illuminate\Support\Facades\Auth;
  24. use Illuminate\Support\Facades\DB;
  25. use Illuminate\Validation\Rules\Unique;
  26. use Wallo\FilamentSelectify\Components\ToggleButton;
  27. class AccountResource extends Resource
  28. {
  29. protected static ?string $model = BankAccount::class;
  30. protected static ?string $modelLabel = 'Account';
  31. protected static ?string $navigationIcon = 'heroicon-o-credit-card';
  32. protected static ?string $navigationGroup = 'Banking';
  33. public static function getModelLabel(): string
  34. {
  35. $modelLabel = static::$modelLabel;
  36. return translate($modelLabel);
  37. }
  38. public static function getNavigationParentItem(): ?string
  39. {
  40. if (Filament::hasTopNavigation()) {
  41. return translate(static::$navigationGroup);
  42. }
  43. return null;
  44. }
  45. public static function form(Form $form): Form
  46. {
  47. return $form
  48. ->schema([
  49. Forms\Components\Section::make('Account Information')
  50. ->schema([
  51. Forms\Components\Select::make('type')
  52. ->options(BankAccountType::class)
  53. ->localizeLabel()
  54. ->searchable()
  55. ->columnSpan(1)
  56. ->default(BankAccountType::DEFAULT)
  57. ->live()
  58. ->afterStateUpdated(static function (Forms\Set $set, $state, ?BankAccount $record, string $operation) {
  59. if ($operation === 'create') {
  60. $set('account.subtype_id', null);
  61. } elseif ($operation === 'edit' && $record !== null) {
  62. if ($state !== $record->type->value) {
  63. $set('account.subtype_id', null);
  64. } else {
  65. $set('account.subtype_id', $record->account->subtype_id);
  66. }
  67. }
  68. })
  69. ->required(),
  70. Forms\Components\Group::make()
  71. ->columnStart(2)
  72. ->relationship('account')
  73. ->schema([
  74. Forms\Components\Select::make('subtype_id')
  75. ->options(static function (Forms\Get $get) {
  76. $typeValue = $get('data.type', true); // Bug: $get('type') returns string on edit, but returns Enum type on create
  77. $typeString = $typeValue instanceof BackedEnum ? $typeValue->value : $typeValue;
  78. return static::groupSubtypesBySubtypeType($typeString);
  79. })
  80. ->localizeLabel()
  81. ->searchable()
  82. ->live()
  83. ->required(),
  84. ]),
  85. Forms\Components\Group::make()
  86. ->relationship('account')
  87. ->columns(2)
  88. ->columnSpanFull()
  89. ->schema([
  90. Forms\Components\TextInput::make('name')
  91. ->maxLength(100)
  92. ->localizeLabel()
  93. ->required(),
  94. Forms\Components\Select::make('currency_code')
  95. ->localizeLabel('Currency')
  96. ->relationship('currency', 'name')
  97. ->default(CurrencyAccessor::getDefaultCurrency())
  98. ->preload()
  99. ->searchable()
  100. ->live()
  101. ->required()
  102. ->createOptionForm([
  103. Forms\Components\Select::make('code')
  104. ->localizeLabel()
  105. ->searchable()
  106. ->options(CurrencyAccessor::getAvailableCurrencies())
  107. ->live()
  108. ->afterStateUpdated(static function (callable $set, $state) {
  109. if ($state === null) {
  110. return;
  111. }
  112. $currency_code = currency($state);
  113. $defaultCurrencyCode = currency()->getCurrency();
  114. $forexEnabled = Forex::isEnabled();
  115. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  116. $set('name', $currency_code->getName() ?? '');
  117. if ($forexEnabled && $exchangeRate !== null) {
  118. $set('rate', $exchangeRate);
  119. }
  120. })
  121. ->required(),
  122. Forms\Components\TextInput::make('name')
  123. ->localizeLabel()
  124. ->maxLength(100)
  125. ->required(),
  126. Forms\Components\TextInput::make('rate')
  127. ->localizeLabel()
  128. ->numeric()
  129. ->required(),
  130. ])->createOptionAction(static function (Forms\Components\Actions\Action $action) {
  131. return $action
  132. ->label('Add Currency')
  133. ->slideOver()
  134. ->modalWidth('md')
  135. ->action(static function (array $data) {
  136. return DB::transaction(static function () use ($data) {
  137. $code = $data['code'];
  138. $name = $data['name'];
  139. $rate = $data['rate'];
  140. return (new CreateCurrency())->create($code, $name, $rate);
  141. });
  142. });
  143. }),
  144. ]),
  145. Forms\Components\Group::make()
  146. ->columns(2)
  147. ->columnSpanFull()
  148. ->schema([
  149. Forms\Components\TextInput::make('number')
  150. ->localizeLabel('Account Number')
  151. ->unique(ignoreRecord: true, modifyRuleUsing: static function (Unique $rule, $state) {
  152. $companyId = Auth::user()->currentCompany->id;
  153. return $rule->where('company_id', $companyId)->where('number', $state);
  154. })
  155. ->maxLength(20)
  156. ->validationAttribute('account number')
  157. ->required(),
  158. ToggleButton::make('enabled')
  159. ->localizeLabel('Default'),
  160. ]),
  161. ])->columns(),
  162. ]);
  163. }
  164. public static function table(Table $table): Table
  165. {
  166. return $table
  167. ->columns([
  168. Tables\Columns\TextColumn::make('account.name')
  169. ->localizeLabel('Account')
  170. ->searchable()
  171. ->weight(FontWeight::Medium)
  172. ->icon(static fn (BankAccount $record) => $record->isEnabled() ? 'heroicon-o-lock-closed' : null)
  173. ->tooltip(static fn (BankAccount $record) => $record->isEnabled() ? 'Default Account' : null)
  174. ->iconPosition('after')
  175. ->description(static fn (BankAccount $record) => $record->mask ?: 'N/A')
  176. ->sortable(),
  177. Tables\Columns\TextColumn::make('account.code') // Just so I could display the balance in the table for now
  178. ->localizeLabel('Current Balance')
  179. ->sortable()
  180. ->formatStateUsing(function (BankAccount $record) {
  181. $accountService = app(AccountService::class);
  182. $startDate = $record->account->company->locale->fiscalYearStartDate();
  183. $endDate = $record->account->company->locale->fiscalYearEndDate();
  184. return $accountService->getEndingBalance($record->account, $startDate, $endDate)?->formatted();
  185. }),
  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. }