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

337 lines
11 KiB
PHP

<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
use App\Models\Amministratore;
use App\Models\Stabile;
use App\Models\Soggetto;
use App\Models\Fornitore;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\File;
class ImportGesconData extends Command
{
/**
* The name and signature of the console command.
*/
protected $signature = 'gescon:import
{--admin-code= : Codice amministratore (8 cifre)}
{--csv-path= : Percorso cartella CSV estratti}
{--test : Modalità test senza modifiche al database}';
/**
* The console command description.
*/
protected $description = 'Importa dati da GESCON nelle tabelle NetGescon esistenti';
protected $amministratore;
protected $testMode = false;
protected $csvPath;
/**
* Execute the console command.
*/
public function handle()
{
$this->info('🔄 NETGESCON - IMPORT DATI GESCON');
$this->info('=====================================');
$this->testMode = $this->option('test');
if ($this->testMode) {
$this->warn('⚠️ MODALITÀ TEST - Nessuna modifica al database');
}
// Verifica codice amministratore
$adminCode = $this->option('admin-code');
if (!$adminCode) {
$adminCode = $this->ask('Inserisci il codice amministratore (8 cifre):');
}
$this->amministratore = Amministratore::where('codice_univoco', $adminCode)->first();
if (!$this->amministratore) {
$this->error("❌ Amministratore con codice {$adminCode} non trovato!");
return 1;
}
$this->info("✅ Amministratore trovato: {$this->amministratore->nome} {$this->amministratore->cognome}");
// Verifica percorso CSV
$this->csvPath = $this->option('csv-path') ?? '/home/michele/netgescon/docs/000-IMPORT/02-CSV-ESTRATTI';
if (!File::exists($this->csvPath)) {
$this->error("❌ Percorso CSV non trovato: {$this->csvPath}");
return 1;
}
$this->info("📂 Percorso CSV: {$this->csvPath}");
// Menu import
$this->showImportMenu();
return 0;
}
protected function showImportMenu()
{
$choice = $this->choice(
'Cosa vuoi importare?',
[
'stabili' => 'Stabili GESCON → stabili NetGescon',
'fornitori' => 'Fornitori GESCON → fornitori NetGescon',
'condomini' => 'Condomini GESCON → soggetti NetGescon',
'all' => 'Tutto (stabili + fornitori + condomini)',
'test' => 'Test connessione e file CSV'
],
'test'
);
switch ($choice) {
case 'stabili':
$this->importStabili();
break;
case 'fornitori':
$this->importFornitori();
break;
case 'condomini':
$this->importCondomini();
break;
case 'all':
$this->importAll();
break;
case 'test':
$this->testImport();
break;
}
}
protected function testImport()
{
$this->info('🧪 TEST CONNESSIONE E FILE CSV');
// Test database
try {
$stabiliCount = Stabile::where('amministratore_id', $this->amministratore->id)->count();
$this->info("✅ Database: {$stabiliCount} stabili per amministratore");
} catch (\Exception $e) {
$this->error("❌ Database: " . $e->getMessage());
return;
}
// Test file CSV
$csvFiles = [
'stabili.csv',
'fornitori.csv',
'condomini_stabile_0021.csv'
];
foreach ($csvFiles as $file) {
$fullPath = $this->csvPath . '/' . $file;
if (File::exists($fullPath)) {
$lines = count(file($fullPath));
$this->info("{$file}: {$lines} righe");
} else {
$this->warn("⚠️ {$file}: Non trovato");
}
}
// Test struttura GESCON
$gesconDirs = File::directories($this->csvPath);
$this->info("📁 Directory GESCON trovate: " . count($gesconDirs));
foreach ($gesconDirs as $dir) {
$dirName = basename($dir);
$csvCount = count(File::glob($dir . '/*.csv'));
$this->line(" - {$dirName}: {$csvCount} file CSV");
}
}
protected function importStabili()
{
$this->info('🏢 IMPORT STABILI GESCON → NETGESCON');
$stabiliCsv = $this->csvPath . '/stabili.csv';
if (!File::exists($stabiliCsv)) {
$this->error("❌ File stabili.csv non trovato in {$this->csvPath}");
return;
}
$handle = fopen($stabiliCsv, 'r');
$header = fgetcsv($handle, 0, ';');
$this->info("📋 Colonne CSV: " . implode(', ', $header));
$imported = 0;
$errors = 0;
while (($row = fgetcsv($handle, 0, ';')) !== false) {
try {
$data = array_combine($header, $row);
if (!$this->testMode) {
$stabile = $this->createStabileFromGescon($data);
$this->line("✅ Importato: {$stabile->denominazione}");
} else {
$this->line("🧪 Test: " . ($data['DENOMINAZIONE'] ?? 'N/A'));
}
$imported++;
} catch (\Exception $e) {
$this->error("❌ Errore riga {$imported}: " . $e->getMessage());
$errors++;
}
}
fclose($handle);
$this->info("📊 Risultato: {$imported} importati, {$errors} errori");
}
protected function createStabileFromGescon($data)
{
return Stabile::create([
'amministratore_id' => $this->amministratore->id,
'codice_stabile' => $data['CODICE_STABILE'] ?? uniqid(),
'denominazione' => $data['DENOMINAZIONE'] ?? 'Stabile GESCON',
'indirizzo' => $data['INDIRIZZO'] ?? '',
'cap' => $data['CAP'] ?? '',
'citta' => $data['CITTA'] ?? '',
'provincia' => $data['PROVINCIA'] ?? '',
'codice_fiscale' => $data['CODICE_FISCALE'] ?? null,
'note' => 'Importato da GESCON - ' . date('Y-m-d H:i:s'),
]);
}
protected function importFornitori()
{
$this->info('🏪 IMPORT FORNITORI GESCON → NETGESCON');
$fornitoriCsv = $this->csvPath . '/fornitori.csv';
if (!File::exists($fornitoriCsv)) {
$this->error("❌ File fornitori.csv non trovato");
return;
}
$handle = fopen($fornitoriCsv, 'r');
$header = fgetcsv($handle, 0, ';');
$imported = 0;
$errors = 0;
while (($row = fgetcsv($handle, 0, ';')) !== false) {
try {
$data = array_combine($header, $row);
if (!$this->testMode) {
$fornitore = $this->createFornitoreFromGescon($data);
$this->line("✅ Importato: {$fornitore->ragione_sociale}");
} else {
$this->line("🧪 Test: " . ($data['RAGIONE_SOCIALE'] ?? 'N/A'));
}
$imported++;
} catch (\Exception $e) {
$this->error("❌ Errore: " . $e->getMessage());
$errors++;
}
}
fclose($handle);
$this->info("📊 Risultato: {$imported} importati, {$errors} errori");
}
protected function createFornitoreFromGescon($data)
{
return Fornitore::create([
'amministratore_id' => $this->amministratore->id,
'ragione_sociale' => $data['RAGIONE_SOCIALE'] ?? $data['DENOMINAZIONE'] ?? 'Fornitore GESCON',
'partita_iva' => $data['PARTITA_IVA'] ?? null,
'codice_fiscale' => $data['CODICE_FISCALE'] ?? null,
'indirizzo' => $data['INDIRIZZO'] ?? '',
'cap' => $data['CAP'] ?? '',
'citta' => $data['CITTA'] ?? '',
'provincia' => $data['PROVINCIA'] ?? '',
'email' => $data['EMAIL'] ?? null,
'pec' => $data['PEC'] ?? null,
'telefono' => $data['TELEFONO'] ?? null,
]);
}
protected function importCondomini()
{
$this->info('👥 IMPORT CONDOMINI GESCON → SOGGETTI NETGESCON');
// Cerca file condomini nelle sottocartelle
$condominiFolders = File::directories($this->csvPath);
$totalImported = 0;
foreach ($condominiFolders as $folder) {
$folderName = basename($folder);
if (strpos($folderName, 'STABILE') !== false) {
$condominiFIle = $folder . '/condomini.csv';
if (File::exists($condominiFIle)) {
$this->info("📂 Elaborando: {$folderName}");
$imported = $this->importCondominiFromFile($condominiFIle, $folderName);
$totalImported += $imported;
}
}
}
$this->info("📊 Totale condomini importati: {$totalImported}");
}
protected function importCondominiFromFile($filePath, $stabile)
{
$handle = fopen($filePath, 'r');
$header = fgetcsv($handle, 0, ';');
$imported = 0;
while (($row = fgetcsv($handle, 0, ';')) !== false) {
try {
$data = array_combine($header, $row);
if (!$this->testMode) {
$soggetto = $this->createSoggettoFromGescon($data, $stabile);
$this->line("{$soggetto->nome} {$soggetto->cognome}");
} else {
$this->line("🧪 Test: " . ($data['COGNOME'] ?? 'N/A'));
}
$imported++;
} catch (\Exception $e) {
$this->error("❌ Errore: " . $e->getMessage());
}
}
fclose($handle);
return $imported;
}
protected function createSoggettoFromGescon($data, $stabile)
{
return Soggetto::create([
'nome' => $data['NOME'] ?? '',
'cognome' => $data['COGNOME'] ?? '',
'ragione_sociale' => $data['DENOMINAZIONE'] ?? null,
'codice_fiscale' => $data['CODICE_FISCALE'] ?? null,
'partita_iva' => $data['PARTITA_IVA'] ?? null,
'email' => $data['EMAIL'] ?? null,
'telefono' => $data['TELEFONO'] ?? null,
'indirizzo' => $data['INDIRIZZO'] ?? '',
'cap' => $data['CAP'] ?? '',
'citta' => $data['CITTA'] ?? '',
'provincia' => $data['PROVINCIA'] ?? '',
'tipo' => 'proprietario', // Default
'codice_univoco' => uniqid(),
]);
}
protected function importAll()
{
$this->info('🔄 IMPORT COMPLETO GESCON');
$this->importStabili();
$this->importFornitori();
$this->importCondomini();
$this->info('✅ Import completo terminato!');
}
}