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 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281
  1. <?php
  2. namespace App\Livewire\Company\Service\ConnectedAccount;
  3. use App\Events\PlaidSuccess;
  4. use App\Events\StartTransactionImport;
  5. use App\Models\Accounting\Account;
  6. use App\Models\Banking\BankAccount;
  7. use App\Models\Banking\ConnectedBankAccount;
  8. use App\Models\Banking\Institution;
  9. use App\Models\User;
  10. use App\Services\AccountService;
  11. use App\Services\PlaidService;
  12. use Filament\Actions\Action;
  13. use Filament\Actions\Concerns\InteractsWithActions;
  14. use Filament\Actions\Contracts\HasActions;
  15. use Filament\Forms\Components\Checkbox;
  16. use Filament\Forms\Components\DatePicker;
  17. use Filament\Forms\Components\Placeholder;
  18. use Filament\Forms\Components\Select;
  19. use Filament\Forms\Concerns\InteractsWithForms;
  20. use Filament\Forms\Contracts\HasForms;
  21. use Filament\Notifications\Notification;
  22. use Filament\Support\Enums\Alignment;
  23. use Illuminate\Contracts\View\View;
  24. use Illuminate\Database\Eloquent\Collection;
  25. use Illuminate\Support\Facades\Auth;
  26. use Illuminate\Support\Facades\Log;
  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. protected AccountService $accountService;
  37. public User $user;
  38. public string $modalWidth;
  39. public function boot(PlaidService $plaidService, AccountService $accountService): void
  40. {
  41. $this->plaidService = $plaidService;
  42. $this->accountService = $accountService;
  43. }
  44. public function mount(): void
  45. {
  46. $this->user = Auth::user();
  47. }
  48. #[Computed]
  49. public function connectedInstitutions(): Collection | array
  50. {
  51. return Institution::withWhereHas('connectedBankAccounts')
  52. ->get();
  53. }
  54. public function getAccountBalance(Account $account): ?string
  55. {
  56. $company = $account->company;
  57. $startDate = $company->locale->fiscalYearStartDate();
  58. $endDate = $company->locale->fiscalYearEndDate();
  59. return $this->accountService->getEndingBalance($account, $startDate, $endDate)?->formatted();
  60. }
  61. public function startImportingTransactions(): Action
  62. {
  63. return Action::make('startImportingTransactions')
  64. ->link()
  65. ->icon('heroicon-o-cloud-arrow-down')
  66. ->label('Start Importing Transactions')
  67. ->modalWidth(fn () => $this->modalWidth)
  68. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  69. ->stickyModalHeader()
  70. ->stickyModalFooter()
  71. ->record(fn (array $arguments) => ConnectedBankAccount::find($arguments['connectedBankAccount']))
  72. ->form([
  73. Placeholder::make('import_from')
  74. ->label('Import Transactions From')
  75. ->content(static fn (ConnectedBankAccount $connectedBankAccount): View => view(
  76. 'components.actions.transaction-import-modal',
  77. compact('connectedBankAccount')
  78. )),
  79. Placeholder::make('info')
  80. ->hiddenLabel()
  81. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  82. ->content(static fn (ConnectedBankAccount $connectedBankAccount) => 'If ' . $connectedBankAccount->name . ' already has transactions for an existing account, select the account to import transactions into.'),
  83. Select::make('bank_account_id')
  84. ->label('Select Account')
  85. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  86. ->options(fn (ConnectedBankAccount $connectedBankAccount) => $this->getBankAccountOptions($connectedBankAccount))
  87. ->required(),
  88. DatePicker::make('start_date')
  89. ->label('Start Date')
  90. ->required()
  91. ->placeholder('Select a start date for importing transactions.'),
  92. ])
  93. ->action(function (array $data, ConnectedBankAccount $connectedBankAccount) {
  94. $selectedBankAccountId = $data['bank_account_id'] ?? $connectedBankAccount->bank_account_id;
  95. $startDate = $data['start_date'];
  96. $company = $this->user->currentCompany;
  97. StartTransactionImport::dispatch($company, $connectedBankAccount, $selectedBankAccountId, $startDate);
  98. unset($this->connectedInstitutions);
  99. });
  100. }
  101. public function getBankAccountOptions(ConnectedBankAccount $connectedBankAccount): array
  102. {
  103. $institutionId = $connectedBankAccount->institution_id ?? null;
  104. $options = ['new' => 'New Account'];
  105. if ($institutionId) {
  106. $options += BankAccount::query()
  107. ->where('company_id', $this->user->currentCompany->id)
  108. ->where('institution_id', $institutionId)
  109. ->whereDoesntHave('connectedBankAccount')
  110. ->with('account')
  111. ->get()
  112. ->pluck('account.name', 'id')
  113. ->toArray();
  114. }
  115. return $options;
  116. }
  117. public function stopImportingTransactions(): Action
  118. {
  119. return Action::make('stopImportingTransactions')
  120. ->link()
  121. ->icon('heroicon-o-stop-circle')
  122. ->label('Stop Importing Transactions')
  123. ->color('danger')
  124. ->requiresConfirmation()
  125. ->modalHeading('Stop Importing Transactions')
  126. ->modalDescription('Importing transactions automatically helps keep your bookkeeping up to date. Are you sure you want to turn this off?')
  127. ->modalSubmitActionLabel('Turn Off')
  128. ->modalCancelActionLabel('Keep On')
  129. ->action(function (array $arguments) {
  130. $connectedBankAccount = ConnectedBankAccount::find($arguments['connectedBankAccount']);
  131. if ($connectedBankAccount) {
  132. $connectedBankAccount->update([
  133. 'import_transactions' => false,
  134. ]);
  135. }
  136. unset($this->connectedInstitutions);
  137. });
  138. }
  139. public function refreshTransactions(): Action
  140. {
  141. return Action::make('refreshTransactions')
  142. ->iconButton()
  143. ->icon('heroicon-o-arrow-path')
  144. ->color('primary')
  145. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  146. ->modalWidth(fn () => $this->modalWidth)
  147. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  148. ->stickyModalHeader()
  149. ->stickyModalFooter()
  150. ->modalHeading('Refresh Transactions')
  151. ->modalSubmitActionLabel('Refresh')
  152. ->form([
  153. Placeholder::make('modalDetails')
  154. ->hiddenLabel()
  155. ->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.'),
  156. Select::make('connected_bank_account_id')
  157. ->label('Select Account')
  158. ->options(fn (Institution $institution) => $institution->getEnabledConnectedBankAccounts()->pluck('name', 'id')->toArray())
  159. ->required(),
  160. ])
  161. ->action(function (array $data) {
  162. $connectedBankAccountId = $data['connected_bank_account_id'];
  163. $connectedBankAccount = ConnectedBankAccount::find($connectedBankAccountId);
  164. $access_token = $connectedBankAccount->access_token;
  165. $this->plaidService->refreshTransactions($access_token);
  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) {
  194. $institutionId = $arguments['institution'];
  195. $institution = Institution::find($institutionId);
  196. if ($institution) {
  197. $institution->connectedBankAccounts()->delete();
  198. }
  199. unset($this->connectedInstitutions);
  200. });
  201. }
  202. #[On('createToken')]
  203. public function createLinkToken(): void
  204. {
  205. $company = $this->user->currentCompany;
  206. $companyLanguage = $company->locale->language ?? 'en';
  207. $companyCountry = $company->profile->country ?? 'US';
  208. $plaidUser = $this->plaidService->createPlaidUser($company);
  209. try {
  210. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  211. $plaidLinkToken = $response->link_token;
  212. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  213. } catch (RuntimeException) {
  214. Log::error('Error creating Plaid token.');
  215. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  216. }
  217. }
  218. #[On('linkSuccess')]
  219. public function handleLinkSuccess($publicToken, $metadata): void
  220. {
  221. $response = $this->plaidService->exchangePublicToken($publicToken);
  222. $accessToken = $response->access_token;
  223. $company = $this->user->currentCompany;
  224. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  225. unset($this->connectedInstitutions);
  226. }
  227. public function sendErrorNotification(string $message): void
  228. {
  229. Notification::make()
  230. ->title('Hold On...')
  231. ->danger()
  232. ->body($message)
  233. ->persistent()
  234. ->send();
  235. }
  236. public function render(): View
  237. {
  238. return view('livewire.company.service.connected-account.list-institutions');
  239. }
  240. }