77 lines
2.6 KiB
PHP
77 lines
2.6 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\RubricaUniversale;
|
|
use App\Models\Stabile;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class GesconFixRubricaCondomini extends Command
|
|
{
|
|
protected $signature = 'gescon:fix-rubrica-condomini
|
|
{amministratore_id? : (Opzionale) limita all\'amministratore_id}
|
|
{--dry-run : Non scrive su DB, mostra solo conteggi}';
|
|
|
|
protected $description = 'Normalizza i record Rubrica collegati agli stabili: categoria=CONDOMINIO e tipo_contatto=persona_giuridica.';
|
|
|
|
public function handle(): int
|
|
{
|
|
$adminId = (int) ($this->argument('amministratore_id') ?? 0);
|
|
$dryRun = (bool) $this->option('dry-run');
|
|
|
|
$stabiliQuery = Stabile::query()
|
|
->whereNotNull('rubrica_id')
|
|
->where('rubrica_id', '>', 0);
|
|
|
|
if ($adminId > 0) {
|
|
$stabiliQuery->where('amministratore_id', $adminId);
|
|
}
|
|
|
|
$rubricaIds = $stabiliQuery->distinct()->pluck('rubrica_id')->map(fn($v) => (int) $v)->filter()->values();
|
|
if ($rubricaIds->isEmpty()) {
|
|
$this->info('Nessun rubrica_id trovato sugli stabili (niente da fare).');
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
$rubricaQuery = RubricaUniversale::query()->whereIn('id', $rubricaIds);
|
|
|
|
$toFix = (clone $rubricaQuery)
|
|
->where(function ($q) {
|
|
$q->whereNull('categoria')
|
|
->orWhere('categoria', '')
|
|
->orWhereNotIn('categoria', ['CONDOMINIO', 'condominio'])
|
|
->orWhereNull('tipo_contatto')
|
|
->orWhere('tipo_contatto', '!=', 'persona_giuridica');
|
|
});
|
|
|
|
$countToFix = (clone $toFix)->count();
|
|
|
|
$this->info('Rubrica stabili trovati: ' . $rubricaIds->count());
|
|
$this->info('Record rubrica da normalizzare: ' . $countToFix . ($dryRun ? ' (dry-run)' : ''));
|
|
|
|
if ($dryRun || $countToFix === 0) {
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
DB::transaction(function () use ($toFix) {
|
|
foreach ($toFix->cursor() as $r) {
|
|
$payload = [
|
|
'categoria' => 'CONDOMINIO',
|
|
'tipo_contatto' => 'persona_giuridica',
|
|
];
|
|
|
|
// Non forziamo ragione_sociale: se già presente ok, altrimenti lasciamo com'è.
|
|
$r->fill($payload);
|
|
if ($r->isDirty()) {
|
|
$r->data_ultima_modifica = now()->toDateString();
|
|
$r->save();
|
|
}
|
|
}
|
|
});
|
|
|
|
$this->info('✅ Normalizzazione completata.');
|
|
return self::SUCCESS;
|
|
}
|
|
}
|