48 lines
2.3 KiB
PHP
48 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Services\Sgc\CalendarDimension;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class PopulateDimTempo extends Command
|
|
{
|
|
protected $signature = 'sgc:populate-dim-tempo {--start-year= : Primeiro ano (por omissão, ano actual)} {--years=10 : Número de anos completos} {--dry-run : Conferir intervalo sem aceder à base}';
|
|
protected $description = 'Insere o calendário em analytics_dim_tempo sem substituir dias existentes';
|
|
|
|
public function handle(): int
|
|
{
|
|
$start = (string) ($this->option('start-year') ?? now('Africa/Maputo')->year);
|
|
$years = (string) $this->option('years');
|
|
if (!ctype_digit($start) || !ctype_digit($years) || (int)$start < 1 || (int)$years < 1 || (int)$years > 100 || (int)$start + (int)$years > 10000) {
|
|
$this->error('Indique um ano válido e entre 1 e 100 anos, até ao ano 9999.');
|
|
return self::INVALID;
|
|
}
|
|
$count = 0;
|
|
if ($this->option('dry-run')) {
|
|
foreach (CalendarDimension::days((int)$start, (int)$years) as $day) $count++;
|
|
$this->info("Simulação: {$count} dias; {$start}-01-01 até ".((int)$start+(int)$years-1).'-12-31. Nenhuma escrita.');
|
|
return self::SUCCESS;
|
|
}
|
|
$connection = DB::connection();
|
|
if (!$connection->getSchemaBuilder()->hasTable('analytics_dim_tempo')) {
|
|
$this->error('Falta analytics_dim_tempo; aplique primeiro a migration analítica.');
|
|
return self::FAILURE;
|
|
}
|
|
$inserted = $connection->transaction(function () use ($connection, $start, $years, &$count) {
|
|
$batch = []; $inserted = 0;
|
|
foreach (CalendarDimension::days((int)$start, (int)$years) as $day) {
|
|
$batch[] = $day; $count++;
|
|
if (count($batch) === 250) {
|
|
$inserted += $connection->table('analytics_dim_tempo')->insertOrIgnore($batch); $batch = [];
|
|
}
|
|
}
|
|
if ($batch) $inserted += $connection->table('analytics_dim_tempo')->insertOrIgnore($batch);
|
|
return $inserted;
|
|
});
|
|
$this->info("Calendário: {$count} dias; {$inserted} inseridos; restantes preservados. Feriados não classificados; dia útil significa apenas segunda a sexta.");
|
|
return self::SUCCESS;
|
|
}
|
|
}
|