Du kan inte välja fler än 25 ämnen Ämnen måste starta med en bokstav eller siffra, kan innehålla bindestreck ('-') och vara max 35 tecken långa.

ListInstitutions.php 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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)
  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)
  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. ->minDate(company_today()->subDays(PlaidService::TRANSACTION_DAYS_REQUESTED)->toDateString())
  84. ->maxDate(company_today()->toDateString()),
  85. ])
  86. ->action(function (array $data, ConnectedBankAccount $connectedBankAccount) {
  87. $selectedBankAccountId = $data['bank_account_id'] ?? $connectedBankAccount->bank_account_id;
  88. $startDate = $data['start_date'];
  89. $company = $this->user->currentCompany;
  90. StartTransactionImport::dispatch($company, $connectedBankAccount, $selectedBankAccountId, $startDate);
  91. unset($this->connectedInstitutions);
  92. });
  93. }
  94. public function getBankAccountOptions(ConnectedBankAccount $connectedBankAccount): array
  95. {
  96. $institutionId = $connectedBankAccount->institution_id ?? null;
  97. $options = ['new' => 'New Account'];
  98. if ($institutionId) {
  99. $accountOptions = BankAccount::query()
  100. ->join('accounts', 'bank_accounts.account_id', '=', 'accounts.id')
  101. ->where('bank_accounts.institution_id', $institutionId)
  102. ->whereDoesntHave('connectedBankAccount')
  103. ->select(['bank_accounts.id', 'accounts.name'])
  104. ->pluck('accounts.name', 'bank_accounts.id')
  105. ->toArray();
  106. $options += $accountOptions;
  107. }
  108. return $options;
  109. }
  110. public function stopImportingTransactions(): Action
  111. {
  112. return Action::make('stopImportingTransactions')
  113. ->link()
  114. ->icon('heroicon-o-stop-circle')
  115. ->label('Stop importing transactions')
  116. ->color('danger')
  117. ->requiresConfirmation()
  118. ->modalHeading('Stop Importing Transactions')
  119. ->modalDescription('Importing transactions automatically helps keep your bookkeeping up to date. Are you sure you want to turn this off?')
  120. ->modalSubmitActionLabel('Turn Off')
  121. ->modalCancelActionLabel('Keep On')
  122. ->action(function (array $arguments) {
  123. $connectedBankAccount = ConnectedBankAccount::find($arguments['connectedBankAccount']);
  124. if ($connectedBankAccount) {
  125. $connectedBankAccount->update([
  126. 'import_transactions' => false,
  127. ]);
  128. }
  129. unset($this->connectedInstitutions);
  130. });
  131. }
  132. public function refreshTransactions(): Action
  133. {
  134. return Action::make('refreshTransactions')
  135. ->iconButton()
  136. ->icon('heroicon-o-arrow-path')
  137. ->color('primary')
  138. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  139. ->modalWidth(fn () => $this->modalWidth)
  140. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  141. ->stickyModalHeader()
  142. ->stickyModalFooter()
  143. ->modalHeading('Refresh Transactions')
  144. ->modalSubmitActionLabel('Refresh')
  145. ->form([
  146. Placeholder::make('modalDetails')
  147. ->hiddenLabel()
  148. ->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.'),
  149. Select::make('connected_bank_account_id')
  150. ->label('Select account')
  151. ->softRequired()
  152. ->selectablePlaceholder(false)
  153. ->hint(
  154. fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->count() . ' ' .
  155. Str::plural('account', $institution->getEnabledConnectedBankAccounts()->count()) . ' available'
  156. )
  157. ->hintColor('primary')
  158. ->options(fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->pluck('name', 'id')->toArray())
  159. ->default(fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->first()?->id),
  160. ])
  161. ->action(function (array $data) {
  162. $connectedBankAccountId = $data['connected_bank_account_id'];
  163. $connectedBankAccount = ConnectedBankAccount::find($connectedBankAccountId);
  164. if ($connectedBankAccount) {
  165. $access_token = $connectedBankAccount->access_token;
  166. $this->plaidService->refreshTransactions($access_token);
  167. }
  168. unset($this->connectedInstitutions);
  169. });
  170. }
  171. public function deleteBankConnection(): Action
  172. {
  173. return Action::make('deleteBankConnection')
  174. ->iconButton()
  175. ->icon('heroicon-o-trash')
  176. ->color('danger')
  177. ->modalHeading('Delete Bank Connection')
  178. ->modalWidth(fn () => $this->modalWidth)
  179. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  180. ->stickyModalHeader()
  181. ->stickyModalFooter()
  182. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  183. ->form([
  184. Placeholder::make('modalDetails')
  185. ->hiddenLabel()
  186. ->content(static fn (Institution $institution): View => view(
  187. 'components.actions.delete-bank-connection-modal',
  188. compact('institution')
  189. )),
  190. Checkbox::make('confirm')
  191. ->label('Yes, I want to delete this bank connection.')
  192. ->markAsRequired(false)
  193. ->required(),
  194. ])
  195. ->action(function (array $arguments, Institution $institution) {
  196. try {
  197. $this->processBankConnectionDeletion($institution);
  198. } catch (RuntimeException $e) {
  199. Log::error('Error deleting bank connection ' . $e->getMessage());
  200. $this->sendErrorNotification("We're currently experiencing issues deleting your bank connection. Please try again in a few moments.");
  201. } finally {
  202. unset($this->connectedInstitutions);
  203. }
  204. });
  205. }
  206. private function processBankConnectionDeletion(Institution $institution): void
  207. {
  208. DB::transaction(function () use ($institution) {
  209. $accessTokens = $institution->connectedBankAccounts->pluck('access_token')->unique()->toArray();
  210. foreach ($accessTokens as $accessToken) {
  211. $this->plaidService->removeItem($accessToken);
  212. }
  213. $institution->connectedBankAccounts()->each(fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->delete());
  214. });
  215. }
  216. #[On('createToken')]
  217. public function createLinkToken(): void
  218. {
  219. try {
  220. $company = $this->user->currentCompany;
  221. $companyLanguage = $company->locale->language ?? 'en';
  222. $companyCountry = $company->profile?->address?->country_code ?? 'US';
  223. $plaidUser = $this->plaidService->createPlaidUser($company);
  224. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  225. $plaidLinkToken = $response->link_token;
  226. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  227. } catch (RuntimeException) {
  228. Log::error('Error creating Plaid token.');
  229. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  230. }
  231. }
  232. #[On('linkSuccess')]
  233. public function handleLinkSuccess($publicToken, $metadata): void
  234. {
  235. $response = $this->plaidService->exchangePublicToken($publicToken);
  236. $accessToken = $response->access_token;
  237. $company = $this->user->currentCompany;
  238. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  239. unset($this->connectedInstitutions);
  240. }
  241. public function sendErrorNotification(string $message): void
  242. {
  243. Notification::make()
  244. ->title('Hold on...')
  245. ->danger()
  246. ->body($message)
  247. ->persistent()
  248. ->send();
  249. }
  250. public function render(): View
  251. {
  252. return view('livewire.company.service.connected-account.list-institutions');
  253. }
  254. }