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.

CreateTax.php 2.2KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. namespace App\Filament\Resources\TaxResource\Pages;
  3. use App\Filament\Resources\TaxResource;
  4. use App\Models\Setting\Tax;
  5. use Filament\Pages\Actions;
  6. use Filament\Resources\Pages\CreateRecord;
  7. use Illuminate\Database\Eloquent\Model;
  8. use Illuminate\Support\Facades\Auth;
  9. use Illuminate\Support\Facades\DB;
  10. class CreateTax extends CreateRecord
  11. {
  12. protected static string $resource = TaxResource::class;
  13. protected function getRedirectUrl(): string
  14. {
  15. return $this->getResource()::getUrl('index');
  16. }
  17. protected function mutateFormDataBeforeCreate(array $data): array
  18. {
  19. $data['company_id'] = Auth::user()->currentCompany->id;
  20. $data['enabled'] = (bool)$data['enabled'];
  21. $data['created_by'] = Auth::id();
  22. return $data;
  23. }
  24. protected function handleRecordCreation(array $data): Model
  25. {
  26. return DB::transaction(function () use ($data) {
  27. $currentCompanyId = auth()->user()->currentCompany->id;
  28. $type = $data['type'] ?? null;
  29. $enabled = (bool)($data['enabled'] ?? false);
  30. if ($enabled === true) {
  31. $this->disableExistingRecord($currentCompanyId, $type);
  32. } else {
  33. $this->ensureAtLeastOneEnabled($currentCompanyId, $type, $enabled);
  34. }
  35. $data['enabled'] = $enabled;
  36. return parent::handleRecordCreation($data);
  37. });
  38. }
  39. protected function disableExistingRecord(int $companyId, string $type): void
  40. {
  41. $existingEnabledRecord = Tax::where('company_id', $companyId)
  42. ->where('enabled', true)
  43. ->where('type', $type)
  44. ->first();
  45. if ($existingEnabledRecord !== null) {
  46. $existingEnabledRecord->enabled = false;
  47. $existingEnabledRecord->save();
  48. }
  49. }
  50. protected function ensureAtLeastOneEnabled(int $companyId, string $type, bool &$enabled): void
  51. {
  52. $otherEnabledRecords = Tax::where('company_id', $companyId)
  53. ->where('enabled', true)
  54. ->where('type', $type)
  55. ->count();
  56. if ($otherEnabledRecords === 0) {
  57. $enabled = true;
  58. }
  59. }
  60. }