Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.

ListInstitutions.php 7.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220
  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\DatePicker;
  14. use Filament\Forms\Components\Select;
  15. use Filament\Forms\Concerns\InteractsWithForms;
  16. use Filament\Forms\Contracts\HasForms;
  17. use Filament\Forms\Form;
  18. use Filament\Forms\Get;
  19. use Filament\Notifications\Notification;
  20. use Filament\Support\Enums\MaxWidth;
  21. use Illuminate\Contracts\View\View;
  22. use Illuminate\Database\Eloquent\Builder;
  23. use Illuminate\Database\Eloquent\Collection;
  24. use Illuminate\Database\Eloquent\Relations\HasMany;
  25. use Illuminate\Support\Facades\Auth;
  26. use Illuminate\Support\Facades\Log;
  27. use JsonException;
  28. use Livewire\Attributes\Computed;
  29. use Livewire\Attributes\On;
  30. use Livewire\Component;
  31. use RuntimeException;
  32. class ListInstitutions extends Component implements HasForms, HasActions
  33. {
  34. use InteractsWithForms;
  35. use InteractsWithActions;
  36. protected PlaidService $plaidService;
  37. public User $user;
  38. public ?ConnectedBankAccount $connectedBankAccount = null;
  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(MaxWidth::TwoExtraLarge)
  60. ->stickyModalHeader()
  61. ->stickyModalFooter()
  62. ->record($this->connectedBankAccount)
  63. ->mountUsing(function (array $arguments, Form $form) {
  64. $connectedAccountId = $arguments['connectedBankAccount'];
  65. $this->connectedBankAccount = ConnectedBankAccount::find($connectedAccountId);
  66. $form
  67. ->fill($this->connectedBankAccount->toArray())
  68. ->operation('edit')
  69. ->model($this->connectedBankAccount);
  70. })
  71. ->form([
  72. Select::make('bank_account_id')
  73. ->label('Select Account')
  74. ->visible(static fn (?ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount?->bank_account_id === null)
  75. ->options(fn () => $this->getBankAccountOptions())
  76. ->required()
  77. ->placeholder('Select an account to start importing transactions for.'),
  78. DatePicker::make('start_date')
  79. ->label('Start Date')
  80. ->required()
  81. ->placeholder('Select a start date for importing transactions.'),
  82. ])
  83. ->action(function (array $arguments, array $data, ConnectedBankAccount $connectedBankAccount) {
  84. $connectedBankAccountId = $arguments['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, $connectedBankAccountId, $selectedBankAccountId, $startDate);
  89. unset($this->connectedInstitutions);
  90. });
  91. }
  92. public function getBankAccountOptions(): array
  93. {
  94. $institutionId = $this->connectedBankAccount->institution_id ?? null;
  95. $options = BankAccount::query()
  96. ->where('company_id', $this->user->currentCompany->id)
  97. ->when($institutionId, static fn($query) => $query->where('institution_id', $institutionId))
  98. ->whereDoesntHave('connectedBankAccount')
  99. ->with('account')
  100. ->get()
  101. ->pluck('account.name', 'id')
  102. ->toArray();
  103. return ['new' => 'New Account'] + $options;
  104. }
  105. public function stopImportingTransactions(): Action
  106. {
  107. return Action::make('stopImportingTransactions')
  108. ->link()
  109. ->icon('heroicon-o-stop-circle')
  110. ->label('Stop Importing Transactions')
  111. ->color('danger')
  112. ->requiresConfirmation()
  113. ->modalHeading('Stop Importing Transactions')
  114. ->modalDescription('Importing transactions automatically helps keep your bookkeeping up to date. Are you sure you want to turn this off?')
  115. ->modalSubmitActionLabel('Turn Off')
  116. ->modalCancelActionLabel('Keep On')
  117. ->action(function (array $arguments) {
  118. $connectedBankAccount = ConnectedBankAccount::find($arguments['connectedBankAccount']);
  119. if ($connectedBankAccount) {
  120. $connectedBankAccount->update([
  121. 'import_transactions' => !$connectedBankAccount->import_transactions,
  122. ]);
  123. }
  124. unset($this->connectedInstitutions);
  125. });
  126. }
  127. public function deleteBankConnection(): Action
  128. {
  129. return Action::make('deleteBankConnection')
  130. ->iconButton()
  131. ->icon('heroicon-o-trash')
  132. ->requiresConfirmation()
  133. ->modalHeading('Delete Bank Connection')
  134. ->modalDescription('Deleting this bank connection will stop the import of transactions for all accounts associated with this bank. Existing transactions will remain unchanged.')
  135. ->action(function (array $arguments) {
  136. $institutionId = $arguments['institution'];
  137. $institution = Institution::find($institutionId);
  138. if ($institution) {
  139. $institution->connectedBankAccounts()->delete();
  140. }
  141. unset($this->connectedInstitutions);
  142. });
  143. }
  144. #[On('createToken')]
  145. public function createLinkToken(): void
  146. {
  147. $company = $this->user->currentCompany;
  148. $companyLanguage = $company->locale->language ?? 'en';
  149. $companyCountry = $company->profile->country ?? 'US';
  150. $plaidUser = $this->plaidService->createPlaidUser($company);
  151. try {
  152. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  153. $plaidLinkToken = $response->link_token;
  154. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  155. } catch (RuntimeException) {
  156. Log::error("Error creating Plaid token.");
  157. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  158. }
  159. }
  160. #[On('linkSuccess')]
  161. public function handleLinkSuccess($publicToken, $metadata): void
  162. {
  163. $response = $this->plaidService->exchangePublicToken($publicToken);
  164. $accessToken = $response->access_token;
  165. $company = $this->user->currentCompany;
  166. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  167. unset($this->connectedInstitutions);
  168. }
  169. public function sendErrorNotification(string $message): void
  170. {
  171. Notification::make()
  172. ->title('Hold On...')
  173. ->danger()
  174. ->body($message)
  175. ->persistent()
  176. ->send();
  177. }
  178. public function render(): View
  179. {
  180. return view('livewire.company.service.connected-account.list-institutions');
  181. }
  182. }