78 lines
2.0 KiB
PHP
78 lines
2.0 KiB
PHP
<?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.");
|
|
}
|
|
}
|