Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. <?php
  2. namespace App\Filament\Resources\CurrencyResource\Pages;
  3. use App\Filament\Resources\CurrencyResource;
  4. use App\Models\Banking\Account;
  5. use App\Models\Setting\Currency;
  6. use Filament\Pages\Actions;
  7. use Filament\Resources\Pages\EditRecord;
  8. use Illuminate\Database\Eloquent\Model;
  9. use Illuminate\Support\Facades\Auth;
  10. use Illuminate\Support\Facades\DB;
  11. class EditCurrency extends EditRecord
  12. {
  13. protected static string $resource = CurrencyResource::class;
  14. protected function getActions(): array
  15. {
  16. return [
  17. Actions\DeleteAction::make(),
  18. ];
  19. }
  20. protected function getRedirectUrl(): string
  21. {
  22. return $this->getResource()::getUrl('index');
  23. }
  24. protected function mutateFormDataBeforeSave(array $data): array
  25. {
  26. $data['company_id'] = Auth::user()->currentCompany->id;
  27. $data['enabled'] = (bool)$data['enabled'];
  28. $data['updated_by'] = Auth::id();
  29. return $data;
  30. }
  31. protected function handleRecordUpdate(Model $record, array $data): Model
  32. {
  33. return DB::transaction(function () use ($record, $data) {
  34. $currentCompanyId = auth()->user()->currentCompany->id;
  35. $recordId = $record->id;
  36. $enabled = (bool)($data['enabled'] ?? false);
  37. // If the record is enabled, disable all other records for the same company
  38. if ($enabled === true) {
  39. $this->disableExistingRecord($currentCompanyId, $recordId);
  40. }
  41. // If the record is disabled, ensure at least one record remains enabled
  42. elseif ($enabled === false) {
  43. $this->ensureAtLeastOneEnabled($currentCompanyId, $recordId, $enabled);
  44. }
  45. $data['enabled'] = $enabled;
  46. return parent::handleRecordUpdate($record, $data);
  47. });
  48. }
  49. protected function disableExistingRecord(int $companyId, int $recordId): void
  50. {
  51. $existingEnabledAccount = Currency::where('company_id', $companyId)
  52. ->where('enabled', true)
  53. ->where('id', '!=', $recordId)
  54. ->first();
  55. if ($existingEnabledAccount !== null) {
  56. $existingEnabledAccount->enabled = false;
  57. $existingEnabledAccount->save();
  58. }
  59. }
  60. protected function ensureAtLeastOneEnabled(int $companyId, int $recordId, bool &$enabled): void
  61. {
  62. $enabledAccountsCount = Currency::where('company_id', $companyId)
  63. ->where('enabled', true)
  64. ->where('id', '!=', $recordId)
  65. ->count();
  66. if ($enabledAccountsCount === 0) {
  67. $enabled = true;
  68. }
  69. }
  70. }