|
| 1 | +<?php |
| 2 | + |
| 3 | +namespace App\Console\Commands; |
| 4 | + |
| 5 | +use App\Jobs\ProcessUserDeletion; |
| 6 | +use App\User; |
| 7 | +use Illuminate\Console\Command; |
| 8 | +use Throwable; |
| 9 | + |
| 10 | +class DeleteUserAccount extends Command |
| 11 | +{ |
| 12 | + protected $signature = 'users:delete-account |
| 13 | + {email : The email address of the account to delete} |
| 14 | + {--dry-run : Show what would be deleted without deleting} |
| 15 | + {--queue : Dispatch deletion through the queue instead of running immediately} |
| 16 | + {--force : Skip confirmation prompt}'; |
| 17 | + |
| 18 | + protected $description = 'Delete a user account by email and reassign related event ownership to the legacy user.'; |
| 19 | + |
| 20 | + public function handle(): int |
| 21 | + { |
| 22 | + $email = mb_strtolower(trim((string) $this->argument('email'))); |
| 23 | + |
| 24 | + /** @var User|null $user */ |
| 25 | + $user = User::withTrashed() |
| 26 | + ->whereRaw('LOWER(email) = ?', [$email]) |
| 27 | + ->first(); |
| 28 | + |
| 29 | + if (!$user) { |
| 30 | + $this->error("No user found for email: {$email}"); |
| 31 | + return self::FAILURE; |
| 32 | + } |
| 33 | + |
| 34 | + $this->info("Found user #{$user->id}: {$user->firstname} {$user->lastname} <{$user->email}>"); |
| 35 | + |
| 36 | + if ($this->option('dry-run')) { |
| 37 | + $this->line('Dry run enabled. No changes were made.'); |
| 38 | + return self::SUCCESS; |
| 39 | + } |
| 40 | + |
| 41 | + if (!$this->option('force')) { |
| 42 | + $confirmed = $this->confirm( |
| 43 | + "This will permanently delete user #{$user->id} ({$user->email}). Continue?", |
| 44 | + false |
| 45 | + ); |
| 46 | + |
| 47 | + if (!$confirmed) { |
| 48 | + $this->line('Cancelled.'); |
| 49 | + return self::SUCCESS; |
| 50 | + } |
| 51 | + } |
| 52 | + |
| 53 | + try { |
| 54 | + if ($this->option('queue')) { |
| 55 | + ProcessUserDeletion::dispatch($user->id); |
| 56 | + $this->info("Deletion job dispatched for user #{$user->id}."); |
| 57 | + return self::SUCCESS; |
| 58 | + } |
| 59 | + |
| 60 | + // Execute immediately for urgent/account-support requests. |
| 61 | + (new ProcessUserDeletion($user->id))->handle(); |
| 62 | + $this->info("User #{$user->id} has been deleted."); |
| 63 | + |
| 64 | + return self::SUCCESS; |
| 65 | + } catch (Throwable $e) { |
| 66 | + $this->error("Failed to delete user #{$user->id}: {$e->getMessage()}"); |
| 67 | + return self::FAILURE; |
| 68 | + } |
| 69 | + } |
| 70 | +} |
0 commit comments