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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238
  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\Log;
  25. use Livewire\Attributes\Computed;
  26. use Livewire\Attributes\On;
  27. use Livewire\Component;
  28. use RuntimeException;
  29. class ListInstitutions extends Component implements HasActions, HasForms
  30. {
  31. use InteractsWithActions;
  32. use InteractsWithForms;
  33. protected PlaidService $plaidService;
  34. public User $user;
  35. public string $modalWidth;
  36. public function boot(PlaidService $plaidService): void
  37. {
  38. $this->plaidService = $plaidService;
  39. }
  40. public function mount(): void
  41. {
  42. $this->user = Auth::user();
  43. }
  44. #[Computed]
  45. public function connectedInstitutions(): Collection | array
  46. {
  47. return Institution::withWhereHas('connectedBankAccounts')
  48. ->get();
  49. }
  50. public function startImportingTransactions(): Action
  51. {
  52. return Action::make('startImportingTransactions')
  53. ->link()
  54. ->icon('heroicon-o-cloud-arrow-down')
  55. ->label('Start Importing Transactions')
  56. ->modalWidth(fn () => $this->modalWidth)
  57. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  58. ->stickyModalHeader()
  59. ->stickyModalFooter()
  60. ->record(fn (array $arguments) => ConnectedBankAccount::find($arguments['connectedBankAccount']))
  61. ->form([
  62. Placeholder::make('import_from')
  63. ->label('Import Transactions From')
  64. ->content(static fn (ConnectedBankAccount $connectedBankAccount): View => view(
  65. 'components.actions.transaction-import-modal',
  66. compact('connectedBankAccount')
  67. )),
  68. Placeholder::make('info')
  69. ->hiddenLabel()
  70. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  71. ->content(static fn (ConnectedBankAccount $connectedBankAccount) => 'If ' . $connectedBankAccount->name . ' already has transactions for an existing account, select the account to import transactions into.'),
  72. Select::make('bank_account_id')
  73. ->label('Select Account')
  74. ->visible(static fn (ConnectedBankAccount $connectedBankAccount) => $connectedBankAccount->bank_account_id === null)
  75. ->options(fn (ConnectedBankAccount $connectedBankAccount) => $this->getBankAccountOptions($connectedBankAccount))
  76. ->required(),
  77. DatePicker::make('start_date')
  78. ->label('Start Date')
  79. ->required()
  80. ->placeholder('Select a start date for importing transactions.'),
  81. ])
  82. ->action(function (array $arguments, array $data, ConnectedBankAccount $connectedBankAccount) {
  83. $selectedBankAccountId = $data['bank_account_id'] ?? $connectedBankAccount->bank_account_id;
  84. $startDate = $data['start_date'];
  85. $company = $this->user->currentCompany;
  86. StartTransactionImport::dispatch($company, $connectedBankAccount, $selectedBankAccountId, $startDate);
  87. unset($this->connectedInstitutions);
  88. });
  89. }
  90. public function getBankAccountOptions(ConnectedBankAccount $connectedBankAccount): array
  91. {
  92. $institutionId = $connectedBankAccount->institution_id ?? null;
  93. $options = ['new' => 'New Account'];
  94. if ($institutionId) {
  95. $options += BankAccount::query()
  96. ->where('company_id', $this->user->currentCompany->id)
  97. ->where('institution_id', $institutionId)
  98. ->whereDoesntHave('connectedBankAccount')
  99. ->with('account')
  100. ->get()
  101. ->pluck('account.name', 'id')
  102. ->toArray();
  103. }
  104. return $options;
  105. }
  106. public function stopImportingTransactions(): Action
  107. {
  108. return Action::make('stopImportingTransactions')
  109. ->link()
  110. ->icon('heroicon-o-stop-circle')
  111. ->label('Stop Importing Transactions')
  112. ->color('danger')
  113. ->requiresConfirmation()
  114. ->modalHeading('Stop Importing Transactions')
  115. ->modalDescription('Importing transactions automatically helps keep your bookkeeping up to date. Are you sure you want to turn this off?')
  116. ->modalSubmitActionLabel('Turn Off')
  117. ->modalCancelActionLabel('Keep On')
  118. ->action(function (array $arguments) {
  119. $connectedBankAccount = ConnectedBankAccount::find($arguments['connectedBankAccount']);
  120. if ($connectedBankAccount) {
  121. $connectedBankAccount->update([
  122. 'import_transactions' => ! $connectedBankAccount->import_transactions,
  123. ]);
  124. }
  125. unset($this->connectedInstitutions);
  126. });
  127. }
  128. public function deleteBankConnection(): Action
  129. {
  130. return Action::make('deleteBankConnection')
  131. ->iconButton()
  132. ->icon('heroicon-o-trash')
  133. ->color('danger')
  134. ->modalHeading('Delete Bank Connection')
  135. ->modalWidth(fn () => $this->modalWidth)
  136. ->modalFooterActionsAlignment(fn () => $this->modalWidth === 'screen' ? Alignment::Center : Alignment::Start)
  137. ->stickyModalHeader()
  138. ->stickyModalFooter()
  139. ->record(fn (array $arguments) => Institution::find($arguments['institution']))
  140. ->form([
  141. Placeholder::make('accounts')
  142. ->hiddenLabel()
  143. ->content(static fn (Institution $institution): View => view(
  144. 'components.actions.delete-bank-connection-modal',
  145. compact('institution')
  146. )),
  147. Placeholder::make('info')
  148. ->hiddenLabel()
  149. ->content('Deleting this bank connection will stop the import of transactions for all accounts associated with this bank. Existing transactions will remain unchanged.'),
  150. Checkbox::make('confirm')
  151. ->label('Yes, I want to delete this bank connection.')
  152. ->markAsRequired(false)
  153. ->required(),
  154. ])
  155. ->action(function (array $arguments) {
  156. $institutionId = $arguments['institution'];
  157. $institution = Institution::find($institutionId);
  158. if ($institution) {
  159. $institution->connectedBankAccounts()->delete();
  160. }
  161. unset($this->connectedInstitutions);
  162. });
  163. }
  164. #[On('createToken')]
  165. public function createLinkToken(): void
  166. {
  167. $company = $this->user->currentCompany;
  168. $companyLanguage = $company->locale->language ?? 'en';
  169. $companyCountry = $company->profile->country ?? 'US';
  170. $plaidUser = $this->plaidService->createPlaidUser($company);
  171. try {
  172. $response = $this->plaidService->createToken($companyLanguage, $companyCountry, $plaidUser, ['transactions']);
  173. $plaidLinkToken = $response->link_token;
  174. $this->dispatch('initializeLink', $plaidLinkToken)->self();
  175. } catch (RuntimeException) {
  176. Log::error('Error creating Plaid token.');
  177. $this->sendErrorNotification("We're currently experiencing issues connecting your account. Please try again in a few moments.");
  178. }
  179. }
  180. #[On('linkSuccess')]
  181. public function handleLinkSuccess($publicToken, $metadata): void
  182. {
  183. $response = $this->plaidService->exchangePublicToken($publicToken);
  184. $accessToken = $response->access_token;
  185. $company = $this->user->currentCompany;
  186. PlaidSuccess::dispatch($publicToken, $accessToken, $company);
  187. unset($this->connectedInstitutions);
  188. }
  189. public function sendErrorNotification(string $message): void
  190. {
  191. Notification::make()
  192. ->title('Hold On...')
  193. ->danger()
  194. ->body($message)
  195. ->persistent()
  196. ->send();
  197. }
  198. public function render(): View
  199. {
  200. return view('livewire.company.service.connected-account.list-institutions');
  201. }
  202. }