89 lines
2.7 KiB
PHP
89 lines
2.7 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\AuditLog;
|
|
use App\Models\Document;
|
|
use Illuminate\Console\Command;
|
|
|
|
class ArchiveExpiredDocuments extends Command
|
|
{
|
|
/**
|
|
* The name and signature of the console command.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $signature = 'documents:archive-expired
|
|
{--dry-run : Preview which documents would be archived}';
|
|
|
|
/**
|
|
* The console command description.
|
|
*
|
|
* @var string
|
|
*/
|
|
protected $description = 'Automatically archive documents that have passed their expiration date';
|
|
|
|
/**
|
|
* Execute the console command.
|
|
*/
|
|
public function handle()
|
|
{
|
|
$dryRun = $this->option('dry-run');
|
|
|
|
// Check if auto-archive is enabled in system settings
|
|
$settings = app(\App\Services\SettingsService::class);
|
|
if (!$settings->isAutoArchiveEnabled()) {
|
|
$this->info('Auto-archive is disabled in system settings.');
|
|
return 0;
|
|
}
|
|
|
|
// Find expired documents that should be auto-archived
|
|
$expiredDocuments = Document::where('status', 'active')
|
|
->where('auto_archive_on_expiry', true)
|
|
->whereNotNull('expires_at')
|
|
->whereDate('expires_at', '<', now())
|
|
->get();
|
|
|
|
if ($expiredDocuments->isEmpty()) {
|
|
$this->info('No expired documents found.');
|
|
return 0;
|
|
}
|
|
|
|
$this->info("Found {$expiredDocuments->count()} expired document(s)");
|
|
|
|
if ($dryRun) {
|
|
$this->warn('DRY RUN - No changes will be made');
|
|
$this->newLine();
|
|
}
|
|
|
|
foreach ($expiredDocuments as $document) {
|
|
$this->line("- {$document->title} (expired: {$document->expires_at->format('Y-m-d')})");
|
|
|
|
if (!$dryRun) {
|
|
$document->archive();
|
|
|
|
AuditLog::create([
|
|
'user_id' => null,
|
|
'action' => 'document.auto_archived',
|
|
'auditable_type' => Document::class,
|
|
'auditable_id' => $document->id,
|
|
'old_values' => ['status' => 'active'],
|
|
'new_values' => ['status' => 'archived'],
|
|
'description' => "Document auto-archived due to expiration on {$document->expires_at->format('Y-m-d')}",
|
|
'ip_address' => '127.0.0.1',
|
|
'user_agent' => 'CLI Auto-Archive',
|
|
]);
|
|
|
|
$this->info(" ✓ Archived");
|
|
}
|
|
}
|
|
|
|
$this->newLine();
|
|
if (!$dryRun) {
|
|
$this->info("Successfully archived {$expiredDocuments->count()} document(s)");
|
|
}
|
|
|
|
return 0;
|
|
}
|
|
}
|