netgescon-day0/app/Console/Commands/SyncSoggettiToPersone.php

68 lines
2.2 KiB
PHP
Executable File

<?php
namespace App\Console\Commands;
use App\Services\Anagrafiche\PersonaSyncService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
class SyncSoggettiToPersone extends Command
{
protected $signature = 'anagrafica:sync-soggetti {--chunk=500 : Dimensione del batch di soggetti da processare} {--ids=* : Elabora solo gli ID indicati} {--dry-run : Simula senza scrivere su database}';
protected $description = 'Popola l\'Anagrafica Unica creando/aggiornando le persone a partire dai soggetti importati.';
public function __construct(private PersonaSyncService $personaSyncService)
{
parent::__construct();
}
public function handle(): int
{
if (!Schema::hasTable('soggetti')) {
$this->error('La tabella soggetti non è disponibile.');
return 1;
}
$dryRun = (bool)$this->option('dry-run');
$chunkSize = max(50, (int)($this->option('chunk') ?? 500));
$ids = array_filter(array_map('intval', $this->option('ids') ?? []));
$query = DB::table('soggetti')->orderBy('id');
if (!empty($ids)) {
$query->whereIn('id', $ids);
}
$processed = 0;
$linked = 0;
$refreshed = 0;
$query->chunkById($chunkSize, function ($rows) use (&$processed, &$linked, &$refreshed, $dryRun) {
foreach ($rows as $row) {
$processed++;
$before = $row->persona_id ?? null;
$personaId = $this->personaSyncService->syncFromSoggettoRecord($row, $dryRun);
if ($personaId && !$before) {
$linked++;
} elseif ($personaId && $before) {
$refreshed++;
}
}
$this->output->write('.');
}, 'id');
$this->newLine();
$this->info("Soggetti elaborati: {$processed}");
$this->info("Nuove anagrafiche collegate: {$linked}");
if ($refreshed) {
$this->info("Anagrafiche aggiornate: {$refreshed}");
}
if ($dryRun) {
$this->warn('Esecuzione DRY-RUN: nessuna modifica salvata.');
}
return 0;
}
}