84 lines
3.0 KiB
PHP
84 lines
3.0 KiB
PHP
<?php
|
|
|
|
namespace App\Console\Commands;
|
|
|
|
use App\Models\Stabile;
|
|
use Illuminate\Console\Command;
|
|
use Illuminate\Support\Facades\Schema;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
class StabiliTransferCommand extends Command
|
|
{
|
|
protected $signature = 'stabili:transfer
|
|
{stabile : ID stabile oppure codice_stabile (es. 0019)}
|
|
{to_amministratore_id : ID amministratore destinazione}
|
|
{--dry-run : Simula senza scrivere}
|
|
{--also-rubrica : Se possibile, aggiorna anche rubrica_universale.amministratore_id (se presente) }';
|
|
|
|
protected $description = 'Trasferisce uno stabile da un amministratore a un altro (soft multi-tenant).';
|
|
|
|
public function handle(): int
|
|
{
|
|
$needle = trim((string) $this->argument('stabile'));
|
|
$toId = (int) $this->argument('to_amministratore_id');
|
|
$dry = (bool) $this->option('dry-run');
|
|
|
|
if ($needle === '') {
|
|
$this->error('Specificare stabile (id o codice)');
|
|
return self::FAILURE;
|
|
}
|
|
if ($toId <= 0) {
|
|
$this->error('to_amministratore_id non valido');
|
|
return self::FAILURE;
|
|
}
|
|
|
|
/** @var Stabile|null $stabile */
|
|
$stabile = null;
|
|
if (ctype_digit($needle)) {
|
|
$stabile = Stabile::query()->find((int) $needle);
|
|
}
|
|
if (! $stabile) {
|
|
$stabile = Stabile::query()->where('codice_stabile', $needle)->first();
|
|
}
|
|
if (! $stabile) {
|
|
$stabile = Stabile::query()->where('codice_stabile', str_pad($needle, 4, '0', STR_PAD_LEFT))->first();
|
|
}
|
|
|
|
if (! $stabile) {
|
|
$this->error('Stabile non trovato: ' . $needle);
|
|
return self::FAILURE;
|
|
}
|
|
|
|
$fromId = (int) ($stabile->amministratore_id ?? 0);
|
|
if ($fromId === $toId) {
|
|
$this->info('Nessuna modifica: stabile già assegnato ad amministratore #' . $toId);
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
$this->line('Stabile #' . $stabile->id . ' codice=' . ($stabile->codice_stabile ?? '') . ' denom=' . ($stabile->denominazione ?? ''));
|
|
$this->line('Da amministratore #' . $fromId . ' → a #' . $toId);
|
|
|
|
if ($dry) {
|
|
$this->warn('Dry-run: nessuna scrittura effettuata.');
|
|
return self::SUCCESS;
|
|
}
|
|
|
|
DB::transaction(function () use ($stabile, $toId): void {
|
|
$stabile->amministratore_id = $toId;
|
|
$stabile->save();
|
|
});
|
|
|
|
// Opzionale: riallinea rubrica se esiste la colonna amministratore_id
|
|
if ((bool) $this->option('also-rubrica') && !empty($stabile->rubrica_id)) {
|
|
if (Schema::hasTable('rubrica_universale') && Schema::hasColumn('rubrica_universale', 'amministratore_id')) {
|
|
DB::table('rubrica_universale')
|
|
->where('id', (int) $stabile->rubrica_id)
|
|
->update(['amministratore_id' => $toId, 'updated_at' => now()]);
|
|
}
|
|
}
|
|
|
|
$this->info('✅ Trasferimento completato.');
|
|
return self::SUCCESS;
|
|
}
|
|
}
|