Files
prn2026/app/Console/Commands/ExportPurgeCommand.php
2026-06-03 08:51:22 +08:00

69 lines
1.8 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\ExportLog;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class ExportPurgeCommand extends Command
{
protected $signature = 'exports:purge {--days=30 : Minimum age in days before an export file is purged}';
protected $description = 'Purge export files older than the configured retention period and mark export_logs records as purged.';
public function handle(): int
{
$days = (int) $this->option('days');
if ($days < 1) {
$this->error('--days must be at least 1.');
return self::FAILURE;
}
$cutoff = now()->subDays($days);
$logs = ExportLog::query()
->whereNull('purged_at')
->where('created_at', '<', $cutoff)
->get();
if ($logs->isEmpty()) {
$this->info("No export files eligible for purge (older than {$days} days).");
return self::SUCCESS;
}
$purged = 0;
$missing = 0;
foreach ($logs as $log) {
$disk = $log->disk ?? 'local';
$path = $log->path;
if ($path && Storage::disk($disk)->exists($path)) {
Storage::disk($disk)->delete($path);
$purged++;
} else {
$missing++;
}
$log->forceFill(['purged_at' => now()])->save();
activity('exports')
->performedOn($log)
->withProperties([
'report_type' => $log->report_type,
'path' => $path,
'retention_days' => $days,
])
->log('export_file_purged');
}
$this->info("Purged {$purged} export file(s). {$missing} record(s) had no file on disk.");
return self::SUCCESS;
}
}