0.1.0
This commit is contained in:
77
app/Console/Commands/CleanupReadingHistories.php
Normal file
77
app/Console/Commands/CleanupReadingHistories.php
Normal file
@@ -0,0 +1,77 @@
|
||||
<?php
|
||||
|
||||
namespace App\Console\Commands;
|
||||
|
||||
use Illuminate\Console\Command;
|
||||
use App\Models\User;
|
||||
|
||||
class CleanupReadingHistories extends Command
|
||||
{
|
||||
/**
|
||||
* The name and signature of the console command.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $signature = 'cleanup:histories
|
||||
{userIds?* : The user ID(s) to clean up (use "all" to clean up for all users)}';
|
||||
|
||||
/**
|
||||
* The console command description.
|
||||
*
|
||||
* @var string
|
||||
*/
|
||||
protected $description = 'Clean up duplicate reading histories for specified or all users';
|
||||
|
||||
/**
|
||||
* Execute the console command.
|
||||
*
|
||||
* @return int
|
||||
*/
|
||||
public function handle()
|
||||
{
|
||||
$userIds = $this->argument('userIds');
|
||||
|
||||
if (empty($userIds)) {
|
||||
$this->error('You must specify user IDs or "all".');
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Handle "all" case
|
||||
if ($userIds === ['all']) {
|
||||
$users = User::all();
|
||||
foreach ($users as $user) {
|
||||
$this->cleanUpForUser($user);
|
||||
}
|
||||
} else {
|
||||
// Ensure user IDs are unique
|
||||
$uniqueUserIds = array_unique($userIds);
|
||||
|
||||
foreach ($uniqueUserIds as $userId) {
|
||||
$user = User::find($userId);
|
||||
if ($user) {
|
||||
$this->cleanUpForUser($user);
|
||||
} else {
|
||||
$this->error("User with ID {$userId} not found.");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
$this->info('Cleanup completed successfully.');
|
||||
return 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Clean up duplicate reading histories for a single user.
|
||||
*
|
||||
* @param \App\Models\User $user
|
||||
* @return void
|
||||
*/
|
||||
protected function cleanUpForUser(User $user): void
|
||||
{
|
||||
$result = $user->cleanUpReadingHistories();
|
||||
|
||||
$keptIds = $result['kept_ids']->toArray(); // Convert Collection to array
|
||||
|
||||
$this->info("User ID {$result['user_id']} - Kept IDs: " . implode(', ', $keptIds) . " - Deleted: {$result['deleted_count']} records.");
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user