您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

CreateCurrency.php 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. <?php
  2. namespace App\Filament\Resources\CurrencyResource\Pages;
  3. use App\Filament\Resources\CurrencyResource;
  4. use App\Models\Setting\Currency;
  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 CreateCurrency extends CreateRecord
  11. {
  12. protected static string $resource = CurrencyResource::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. $enabled = (bool)($data['enabled'] ?? false); // Ensure $enabled is always a boolean
  29. if ($enabled === true) {
  30. $this->disableExistingRecord($currentCompanyId);
  31. } else {
  32. $this->ensureAtLeastOneEnabled($currentCompanyId, $enabled);
  33. }
  34. $data['enabled'] = $enabled;
  35. return parent::handleRecordCreation($data);
  36. });
  37. }
  38. protected function disableExistingRecord($companyId): void
  39. {
  40. $existingEnabledRecord = Currency::where('company_id', $companyId)
  41. ->where('enabled', true)
  42. ->first();
  43. if ($existingEnabledRecord !== null) {
  44. $existingEnabledRecord->enabled = false;
  45. $existingEnabledRecord->save();
  46. }
  47. }
  48. protected function ensureAtLeastOneEnabled($companyId, &$enabled): void
  49. {
  50. $enabledAccountsCount = Currency::where('company_id', $companyId)
  51. ->where('enabled', true)
  52. ->count();
  53. if ($enabledAccountsCount === 0) {
  54. $enabled = true;
  55. }
  56. }
  57. }