Vous ne pouvez pas sélectionner plus de 25 sujets Les noms de sujets doivent commencer par une lettre ou un nombre, peuvent contenir des tirets ('-') et peuvent comporter jusqu'à 35 caractères.

AccountResource.php 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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\Utilities\Currency\CurrencyAccessor;
  11. use BackedEnum;
  12. use Filament\Forms;
  13. use Filament\Forms\Form;
  14. use Filament\Resources\Resource;
  15. use Filament\Support\Enums\FontWeight;
  16. use Filament\Tables;
  17. use Filament\Tables\Table;
  18. use Illuminate\Support\Collection;
  19. use Illuminate\Support\Facades\Auth;
  20. use Illuminate\Support\Facades\DB;
  21. use Illuminate\Validation\Rules\Unique;
  22. use Wallo\FilamentSelectify\Components\ToggleButton;
  23. class AccountResource extends Resource
  24. {
  25. protected static ?string $model = BankAccount::class;
  26. protected static ?string $modelLabel = 'Account';
  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\Section::make('Account Information')
  37. ->schema([
  38. Forms\Components\Select::make('type')
  39. ->options(BankAccountType::class)
  40. ->localizeLabel()
  41. ->searchable()
  42. ->columnSpan(1)
  43. ->default(BankAccountType::DEFAULT)
  44. ->live()
  45. ->afterStateUpdated(static function (Forms\Set $set, $state, ?BankAccount $record, string $operation) {
  46. if ($operation === 'create') {
  47. $set('account.subtype_id', null);
  48. } elseif ($operation === 'edit' && $record !== null) {
  49. if ($state !== $record->type->value) {
  50. $set('account.subtype_id', null);
  51. } else {
  52. $set('account.subtype_id', $record->account->subtype_id);
  53. }
  54. }
  55. })
  56. ->required(),
  57. Forms\Components\Group::make()
  58. ->columnStart(2)
  59. ->relationship('account')
  60. ->schema([
  61. Forms\Components\Select::make('subtype_id')
  62. ->options(static function (Forms\Get $get) {
  63. $typeValue = $get('data.type', true); // Bug: $get('type') returns string on edit, but returns Enum type on create
  64. $typeString = $typeValue instanceof BackedEnum ? $typeValue->value : $typeValue;
  65. return static::groupSubtypesBySubtypeType($typeString);
  66. })
  67. ->localizeLabel()
  68. ->searchable()
  69. ->live()
  70. ->required(),
  71. ]),
  72. Forms\Components\Group::make()
  73. ->relationship('account')
  74. ->columns(2)
  75. ->columnSpanFull()
  76. ->schema([
  77. Forms\Components\TextInput::make('name')
  78. ->maxLength(100)
  79. ->localizeLabel()
  80. ->required(),
  81. Forms\Components\Select::make('currency_code')
  82. ->localizeLabel('Currency')
  83. ->relationship('currency', 'name')
  84. ->default(CurrencyAccessor::getDefaultCurrency())
  85. ->preload()
  86. ->searchable()
  87. ->live()
  88. ->required()
  89. ->createOptionForm([
  90. Forms\Components\Select::make('code')
  91. ->localizeLabel()
  92. ->searchable()
  93. ->options(CurrencyAccessor::getAvailableCurrencies())
  94. ->live()
  95. ->afterStateUpdated(static function (callable $set, $state) {
  96. if ($state === null) {
  97. return;
  98. }
  99. $currency_code = currency($state);
  100. $defaultCurrencyCode = currency()->getCurrency();
  101. $forexEnabled = Forex::isEnabled();
  102. $exchangeRate = $forexEnabled ? Forex::getCachedExchangeRate($defaultCurrencyCode, $state) : null;
  103. $set('name', $currency_code->getName() ?? '');
  104. if ($forexEnabled && $exchangeRate !== null) {
  105. $set('rate', $exchangeRate);
  106. }
  107. })
  108. ->required(),
  109. Forms\Components\TextInput::make('name')
  110. ->localizeLabel()
  111. ->maxLength(100)
  112. ->required(),
  113. Forms\Components\TextInput::make('rate')
  114. ->localizeLabel()
  115. ->numeric()
  116. ->required(),
  117. ])->createOptionAction(static function (Forms\Components\Actions\Action $action) {
  118. return $action
  119. ->label('Add Currency')
  120. ->slideOver()
  121. ->modalWidth('md')
  122. ->action(static function (array $data) {
  123. return DB::transaction(static function () use ($data) {
  124. $code = $data['code'];
  125. $name = $data['name'];
  126. $rate = $data['rate'];
  127. return (new CreateCurrency())->create($code, $name, $rate);
  128. });
  129. });
  130. }),
  131. ]),
  132. Forms\Components\Group::make()
  133. ->columns()
  134. ->columnSpanFull()
  135. ->schema([
  136. Forms\Components\TextInput::make('number')
  137. ->localizeLabel('Account Number')
  138. ->unique(ignoreRecord: true, modifyRuleUsing: static function (Unique $rule, $state) {
  139. $companyId = Auth::user()->currentCompany->id;
  140. return $rule->where('company_id', $companyId)->where('number', $state);
  141. })
  142. ->maxLength(20)
  143. ->validationAttribute('account number'),
  144. ToggleButton::make('enabled')
  145. ->localizeLabel('Default'),
  146. ]),
  147. ])->columns(),
  148. ]);
  149. }
  150. public static function table(Table $table): Table
  151. {
  152. return $table
  153. ->columns([
  154. Tables\Columns\TextColumn::make('account.name')
  155. ->localizeLabel('Account')
  156. ->searchable()
  157. ->weight(FontWeight::Medium)
  158. ->icon(static fn (BankAccount $record) => $record->isEnabled() ? 'heroicon-o-lock-closed' : null)
  159. ->tooltip(static fn (BankAccount $record) => $record->isEnabled() ? 'Default Account' : null)
  160. ->iconPosition('after')
  161. ->description(static fn (BankAccount $record) => $record->mask ?? null)
  162. ->sortable(),
  163. Tables\Columns\TextColumn::make('account.ending_balance')
  164. ->localizeLabel('Current Balance')
  165. ->state(static fn (BankAccount $record) => $record->account->ending_balance->convert()->formatWithCode())
  166. ->sortable(),
  167. ])
  168. ->filters([
  169. //
  170. ])
  171. ->actions([
  172. Tables\Actions\EditAction::make(),
  173. ])
  174. ->bulkActions([
  175. Tables\Actions\BulkActionGroup::make([
  176. Tables\Actions\DeleteBulkAction::make()
  177. ->requiresConfirmation()
  178. ->modalDescription('Are you sure you want to delete the selected accounts? All transactions associated with the accounts will be deleted as well.'),
  179. ]),
  180. ])
  181. ->checkIfRecordIsSelectableUsing(static function (BankAccount $record) {
  182. return $record->isDisabled();
  183. })
  184. ->emptyStateActions([
  185. Tables\Actions\CreateAction::make(),
  186. ]);
  187. }
  188. public static function getPages(): array
  189. {
  190. return [
  191. 'index' => Pages\ListAccounts::route('/'),
  192. 'create' => Pages\CreateAccount::route('/create'),
  193. 'edit' => Pages\EditAccount::route('/{record}/edit'),
  194. ];
  195. }
  196. public static function groupSubtypesBySubtypeType($typeString): array
  197. {
  198. $category = match ($typeString) {
  199. BankAccountType::Depository->value, BankAccountType::Investment->value => AccountCategory::Asset,
  200. BankAccountType::Credit->value, BankAccountType::Loan->value => AccountCategory::Liability,
  201. default => null,
  202. };
  203. if ($category === null) {
  204. return [];
  205. }
  206. $subtypes = AccountSubtype::where('category', $category)->get();
  207. return $subtypes->groupBy(fn (AccountSubtype $subtype) => $subtype->type->getLabel())
  208. ->map(fn (Collection $subtypes, string $type) => $subtypes->mapWithKeys(static fn (AccountSubtype $subtype) => [$subtype->id => $subtype->name]))
  209. ->toArray();
  210. }
  211. }