46 lines
2.0 KiB
PHP
46 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Services\TerritorialCsvAudit;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
use Illuminate\Support\Facades\File;
|
|
use Illuminate\Support\Str;
|
|
use Throwable;
|
|
|
|
class AuditTerritorialCsv extends Command
|
|
{
|
|
protected $signature = 'geo:audit-csv {path : CSV UTF-8 do contrato INE}';
|
|
|
|
protected $description = 'Arquivar e validar um CSV territorial sem alterar o cadastro';
|
|
|
|
public function handle(TerritorialCsvAudit $audit): int
|
|
{
|
|
$path = (string) $this->argument('path');
|
|
if (! is_file($path) || ! is_readable($path) || filesize($path) > 20 * 1024 * 1024) {
|
|
$this->error('CSV inacessível ou superior a 20 MiB.');
|
|
|
|
return self::FAILURE;
|
|
}
|
|
$directory = storage_path('app/private/geo-csv-audits/'.Str::uuid());
|
|
File::ensureDirectoryExists($directory, 0700);
|
|
try {
|
|
if (! copy($path, $directory.'/original.csv')) {
|
|
throw new \RuntimeException('Não foi possível arquivar o original.');
|
|
}
|
|
$codes = DB::table('geo_locations as p')->join('geo_locations as c', 'p.parent_id', '=', 'c.id')
|
|
->where('p.location_type', 'province')->where('c.location_type', 'country')->where('c.code', '508')
|
|
->whereNull('p.deleted_at')->whereNull('c.deleted_at')->pluck('p.code')->map(fn ($code) => (string) $code)->all();
|
|
$report = $audit->inspect($directory.'/original.csv', array_values($codes));
|
|
} catch (Throwable $exception) {
|
|
$report = ['status' => 'rejected', 'error' => $exception->getMessage()];
|
|
}
|
|
File::put($directory.'/report.json', json_encode($report, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR));
|
|
$this->info('Relatório privado: '.$directory.'/report.json');
|
|
$this->info('Nenhum território foi criado ou aprovado.');
|
|
|
|
return $report['status'] === 'rejected' ? self::FAILURE : self::SUCCESS;
|
|
}
|
|
}
|