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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  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 $arguments, 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' => ! $connectedBankAccount->import_transactions,
  134. ]);
  135. }
  136. unset($this->connectedInstitutions);
  137. });
  138. }
  139. public function deleteBankConnection(): Action
  140. {
  141. return Action::make('deleteBankConnection')
  142. ->iconButton()
  143. ->icon('heroicon-o-trash')
  144. ->color('danger')
  145. ->modalHeading('Delete Bank Connection')
  146. ->modalWidth(fn () => $this->modalWidth)
  147. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  148. ->stickyModalHeader()
  149. ->stickyModalFooter()
  150. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  151. ->form([
  152. Placeholder::make('accounts')
  153. ->hiddenLabel()
  154. ->content(static fn (Institution $institution): View => view(
  155. 'components.actions.delete-bank-connection-modal',
  156. compact('institution')
  157. )),
  158. Placeholder::make('info')
  159. ->hiddenLabel()
  160. ->content('Deleting this bank connection will stop the import of transactions for all accounts associated with this bank. Existing transactions will remain unchanged.'),
  161. Checkbox::make('confirm')
  162. ->label('Yes, I want to delete this bank connection.')
  163. ->markAsRequired(false)
  164. ->required(),
  165. ])
  166. ->action(function (array $arguments) {
  167. $institutionId = $arguments['institution'];
  168. $institution = Institution::find($institutionId);
  169. if ($institution) {
  170. $institution->connectedBankAccounts()->delete();
  171. }
  172. unset($this->connectedInstitutions);
  173. });
  174. }
  175. #[On('createToken')]
  176. public function createLinkToken(): void
  177. {
  178. $company = $this->user->currentCompany;
  179. $companyLanguage = $company->locale->language ?? 'en';
  180. $companyCountry = $company->profile->country ?? 'US';
  181. $plaidUser = $this->plaidService->createPlaidUser($company);
  182. try {
  183. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  184. $plaidLinkToken = $response->link_token;
  185. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  186. } catch (RuntimeException) {
  187. Log::error('Error creating Plaid token.');
  188. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  189. }
  190. }
  191. #[On('linkSuccess')]
  192. public function handleLinkSuccess($publicToken, $metadata): void
  193. {
  194. $response = $this->plaidService->exchangePublicToken($publicToken);
  195. $accessToken = $response->access_token;
  196. $company = $this->user->currentCompany;
  197. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  198. unset($this->connectedInstitutions);
  199. }
  200. public function sendErrorNotification(string $message): void
  201. {
  202. Notification::make()
  203. ->title('Hold On...')
  204. ->danger()
  205. ->body($message)
  206. ->persistent()
  207. ->send();
  208. }
  209. public function render(): View
  210. {
  211. return view('livewire.company.service.connected-account.list-institutions');
  212. }
  213. }