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

ListInstitutions.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292
  1. <?php
  2. namespace App\Livewire\Company\Service\ConnectedAccount;
  3. use App\Events\PlaidSuccess;
  4. use App\Events\StartTransactionImport;
  5. use App\Models\Banking\BankAccount;
  6. use App\Models\Banking\ConnectedBankAccount;
  7. use App\Models\Banking\Institution;
  8. use App\Models\User;
  9. use App\Services\PlaidService;
  10. use Filament\Actions\Action;
  11. use Filament\Actions\Concerns\InteractsWithActions;
  12. use Filament\Actions\Contracts\HasActions;
  13. use Filament\Forms\Components\Checkbox;
  14. use Filament\Forms\Components\DatePicker;
  15. use Filament\Forms\Components\Placeholder;
  16. use Filament\Forms\Components\Select;
  17. use Filament\Forms\Concerns\InteractsWithForms;
  18. use Filament\Forms\Contracts\HasForms;
  19. use Filament\Notifications\Notification;
  20. use Filament\Support\Enums\Alignment;
  21. use Illuminate\Contracts\View\View;
  22. use Illuminate\Database\Eloquent\Collection;
  23. use Illuminate\Support\Facades\Auth;
  24. use Illuminate\Support\Facades\DB;
  25. use Illuminate\Support\Facades\Log;
  26. use Illuminate\Support\Str;
  27. use Livewire\Attributes\Computed;
  28. use Livewire\Attributes\On;
  29. use Livewire\Component;
  30. use RuntimeException;
  31. class ListInstitutions extends Component implements HasActions, HasForms
  32. {
  33. use InteractsWithActions;
  34. use InteractsWithForms;
  35. protected PlaidService $plaidService;
  36. public User $user;
  37. public string $modalWidth;
  38. public function boot(PlaidService $plaidService): void
  39. {
  40. $this->plaidService = $plaidService;
  41. }
  42. public function mount(): void
  43. {
  44. $this->user = Auth::user();
  45. }
  46. #[Computed]
  47. public function connectedInstitutions(): Collection | array
  48. {
  49. return Institution::withWhereHas('connectedBankAccounts')
  50. ->get();
  51. }
  52. public function startImportingTransactions(): Action
  53. {
  54. return Action::make('startImportingTransactions')
  55. ->link()
  56. ->icon('heroicon-o-cloud-arrow-down')
  57. ->label('Start importing transactions')
  58. ->modalWidth(fn () => $this->modalWidth)
  59. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  60. ->stickyModalHeader()
  61. ->stickyModalFooter()
  62. ->record(fn (array $arguments) => ConnectedBankAccount::find($arguments['connectedBankAccount']))
  63. ->form([
  64. Placeholder::make('import_from')
  65. ->label('Import transactions from')
  66. ->content(static fn (ConnectedBankAccount $connectedBankAccount): View => view(
  67. 'components.actions.transaction-import-modal',
  68. compact('connectedBankAccount')
  69. )),
  70. Placeholder::make('info')
  71. ->hiddenLabel()
  72. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  73. ->content(static fn (ConnectedBankAccount $connectedBankAccount) => 'If ' . $connectedBankAccount->name . ' already has transactions for an existing account, select the account to import transactions into.'),
  74. Select::make('bank_account_id')
  75. ->label('Select account')
  76. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  77. ->options(fn (ConnectedBankAccount $connectedBankAccount) => $this->getBankAccountOptions($connectedBankAccount))
  78. ->required(),
  79. DatePicker::make('start_date')
  80. ->label('Start date')
  81. ->required()
  82. ->placeholder('Select a start date for importing transactions.'),
  83. ])
  84. ->action(function (array $data, ConnectedBankAccount $connectedBankAccount) {
  85. $selectedBankAccountId = $data['bank_account_id'] ?? $connectedBankAccount->bank_account_id;
  86. $startDate = $data['start_date'];
  87. $company = $this->user->currentCompany;
  88. StartTransactionImport::dispatch($company, $connectedBankAccount, $selectedBankAccountId, $startDate);
  89. unset($this->connectedInstitutions);
  90. });
  91. }
  92. public function getBankAccountOptions(ConnectedBankAccount $connectedBankAccount): array
  93. {
  94. $institutionId = $connectedBankAccount->institution_id ?? null;
  95. $options = ['new' => 'New Account'];
  96. if ($institutionId) {
  97. $options += BankAccount::query()
  98. ->where('company_id', $this->user->currentCompany->id)
  99. ->where('institution_id', $institutionId)
  100. ->whereDoesntHave('connectedBankAccount')
  101. ->with('account')
  102. ->get()
  103. ->pluck('account.name', 'id')
  104. ->toArray();
  105. }
  106. return $options;
  107. }
  108. public function stopImportingTransactions(): Action
  109. {
  110. return Action::make('stopImportingTransactions')
  111. ->link()
  112. ->icon('heroicon-o-stop-circle')
  113. ->label('Stop importing transactions')
  114. ->color('danger')
  115. ->requiresConfirmation()
  116. ->modalHeading('Stop Importing Transactions')
  117. ->modalDescription('Importing transactions automatically helps keep your bookkeeping up to date. Are you sure you want to turn this off?')
  118. ->modalSubmitActionLabel('Turn Off')
  119. ->modalCancelActionLabel('Keep On')
  120. ->action(function (array $arguments) {
  121. $connectedBankAccount = ConnectedBankAccount::find($arguments['connectedBankAccount']);
  122. if ($connectedBankAccount) {
  123. $connectedBankAccount->update([
  124. 'import_transactions' => false,
  125. ]);
  126. }
  127. unset($this->connectedInstitutions);
  128. });
  129. }
  130. public function refreshTransactions(): Action
  131. {
  132. return Action::make('refreshTransactions')
  133. ->iconButton()
  134. ->icon('heroicon-o-arrow-path')
  135. ->color('primary')
  136. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  137. ->modalWidth(fn () => $this->modalWidth)
  138. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  139. ->stickyModalHeader()
  140. ->stickyModalFooter()
  141. ->modalHeading('Refresh Transactions')
  142. ->modalSubmitActionLabel('Refresh')
  143. ->form([
  144. Placeholder::make('modalDetails')
  145. ->hiddenLabel()
  146. ->content('Refreshing transactions will update the selected account with the latest transactions from the bank if there are any new transactions available. This may take a few moments.'),
  147. Select::make('connected_bank_account_id')
  148. ->label('Select account')
  149. ->softRequired()
  150. ->selectablePlaceholder(false)
  151. ->hint(
  152. fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->count() . ' ' .
  153. Str::plural('account', $institution->getEnabledConnectedBankAccounts()->count()) . ' available'
  154. )
  155. ->hintColor('primary')
  156. ->options(fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->pluck('name', 'id')->toArray())
  157. ->default(fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->first()?->id),
  158. ])
  159. ->action(function (array $data) {
  160. $connectedBankAccountId = $data['connected_bank_account_id'];
  161. $connectedBankAccount = ConnectedBankAccount::find($connectedBankAccountId);
  162. if ($connectedBankAccount) {
  163. $access_token = $connectedBankAccount->access_token;
  164. $this->plaidService->refreshTransactions($access_token);
  165. }
  166. unset($this->connectedInstitutions);
  167. });
  168. }
  169. public function deleteBankConnection(): Action
  170. {
  171. return Action::make('deleteBankConnection')
  172. ->iconButton()
  173. ->icon('heroicon-o-trash')
  174. ->color('danger')
  175. ->modalHeading('Delete Bank Connection')
  176. ->modalWidth(fn () => $this->modalWidth)
  177. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  178. ->stickyModalHeader()
  179. ->stickyModalFooter()
  180. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  181. ->form([
  182. Placeholder::make('modalDetails')
  183. ->hiddenLabel()
  184. ->content(static fn (Institution $institution): View => view(
  185. 'components.actions.delete-bank-connection-modal',
  186. compact('institution')
  187. )),
  188. Checkbox::make('confirm')
  189. ->label('Yes, I want to delete this bank connection.')
  190. ->markAsRequired(false)
  191. ->required(),
  192. ])
  193. ->action(function (array $arguments, Institution $institution) {
  194. try {
  195. $this->processBankConnectionDeletion($institution);
  196. } catch (RuntimeException $e) {
  197. Log::error('Error deleting bank connection ' . $e->getMessage());
  198. $this->sendErrorNotification("We're currently experiencing issues deleting your bank connection. Please try again in a few moments.");
  199. } finally {
  200. unset($this->connectedInstitutions);
  201. }
  202. });
  203. }
  204. private function processBankConnectionDeletion(Institution $institution): void
  205. {
  206. DB::transaction(function () use ($institution) {
  207. $accessTokens = $institution->connectedBankAccounts->pluck('access_token')->unique()->toArray();
  208. foreach ($accessTokens as $accessToken) {
  209. $this->plaidService->removeItem($accessToken);
  210. }
  211. $institution->connectedBankAccounts()->each(fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->delete());
  212. });
  213. }
  214. #[On('createToken')]
  215. public function createLinkToken(): void
  216. {
  217. try {
  218. $company = $this->user->currentCompany;
  219. $companyLanguage = $company->locale->language ?? 'en';
  220. $companyCountry = $company->profile?->address?->country_code ?? 'US';
  221. $plaidUser = $this->plaidService->createPlaidUser($company);
  222. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  223. $plaidLinkToken = $response->link_token;
  224. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  225. } catch (RuntimeException) {
  226. Log::error('Error creating Plaid token.');
  227. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  228. }
  229. }
  230. #[On('linkSuccess')]
  231. public function handleLinkSuccess($publicToken, $metadata): void
  232. {
  233. $response = $this->plaidService->exchangePublicToken($publicToken);
  234. $accessToken = $response->access_token;
  235. $company = $this->user->currentCompany;
  236. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  237. unset($this->connectedInstitutions);
  238. }
  239. public function sendErrorNotification(string $message): void
  240. {
  241. Notification::make()
  242. ->title('Hold on...')
  243. ->danger()
  244. ->body($message)
  245. ->persistent()
  246. ->send();
  247. }
  248. public function render(): View
  249. {
  250. return view('livewire.company.service.connected-account.list-institutions');
  251. }
  252. }