Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

AccountResource.php 15KB

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