選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

AccountResource.php 15KB

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