You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ListInstitutions.php 12KB

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