Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

AccountResource.php 15KB

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