netgescon-day0/app/Services/GesconImport/Micro/StabiliMicroImporter.php

110 lines
5.0 KiB
PHP

<?php
namespace App\Services\GesconImport\Micro;
use App\Models\Stabile;
use App\Models\Amministratore;
use App\Models\UserSetting;
use Illuminate\Support\Facades\DB;
class StabiliMicroImporter
{
/**
* Importa rapidamente un singolo stabile da MDB o staging minimale.
* Ritorna array [created=>int, updated=>int, stabile_id=>int|null, data=>array].
*/
public function import(string $legacyCode, Amministratore $amministratore, array $mapping = []): array
{
$legacyCode = trim($legacyCode);
if ($legacyCode === '') {
return ['created'=>0,'updated'=>0,'stabile_id'=>null,'data'=>[]];
}
// Recupera record sorgente (ordine di priorità: staging -> MDB)
$row = $this->fetchFromStaging($legacyCode) ?: $this->fetchFromMdb($legacyCode) ?: [];
if (empty($row)) {
return ['created'=>0,'updated'=>0,'stabile_id'=>null,'data'=>[]];
}
// Applica mapping semplice campo->target (solo campi stabile.* supportati qui)
$payload = [
'amministratore_id' => $amministratore->id,
'attivo' => true,
'note' => 'Import GESCON micro',
];
foreach ($mapping as $legacyKey => $target) {
if (!isset($row[$legacyKey]) || !is_string($target)) continue;
if (str_starts_with($target, 'stabile.')) {
$field = substr($target, 8);
$payload[$field] = is_string($row[$legacyKey]) ? trim($row[$legacyKey]) : $row[$legacyKey];
}
}
// Codice stabile: fallback legacyCode
if (empty($payload['codice_stabile'])) {
$payload['codice_stabile'] = $legacyCode;
}
$existing = Stabile::where('amministratore_id', $amministratore->id)
->where(function($q) use ($legacyCode){
$q->where('codice_stabile',$legacyCode)->orWhere('codice_interno',$legacyCode);
})->first();
if ($existing) {
$existing->update($payload);
return ['created'=>0,'updated'=>1,'stabile_id'=>$existing->id,'data'=>$row];
}
$created = Stabile::create($payload);
return ['created'=>1,'updated'=>0,'stabile_id'=>$created->id,'data'=>$row];
}
private function fetchFromStaging(string $legacyCode): ?array
{
try {
if (DB::connection('gescon_import')->getSchemaBuilder()->hasTable('stabili')) {
$rec = DB::connection('gescon_import')->table('stabili')
->where('cod_stabile',$legacyCode)
->orWhere('nome_directory',$legacyCode)
->orWhere('internet_cod_stab',$legacyCode)
->first();
if ($rec) return (array)$rec;
}
if (DB::connection('gescon_import')->getSchemaBuilder()->hasTable('condomin')) {
$rec = DB::connection('gescon_import')->table('condomin')
->where('cod_stabile',$legacyCode)
->first();
if ($rec) return (array)$rec;
}
} catch (\Throwable $e) {}
return null;
}
private function fetchFromMdb(string $legacyCode): ?array
{
$mdb = UserSetting::get('gescon.mdb_stabili', '/mnt/gescon-archives/gescon/dbc/Stabili.mdb');
$hasTools = trim((string)@shell_exec('command -v mdb-export')) !== '';
if (!$hasTools || !is_file($mdb) || !is_readable($mdb)) return null;
try {
$tmp = tempnam(sys_get_temp_dir(),'mdbcsv_');
$table = 'Stabili';
$tables = @shell_exec(sprintf('%s -1 %s 2>/dev/null','mdb-tables',escapeshellarg($mdb))) ?: '';
foreach (preg_split('/\r?\n/', trim($tables)) as $t){
if (preg_match('/stabil/i',$t)){ $table=trim($t); break; }
}
$cmd = sprintf('%s -D %s -d %s -q %s -R "\\n" %s %s > %s 2>/dev/null',
'mdb-export','%Y-%m-%d','|','"',escapeshellarg($mdb),escapeshellarg($table),escapeshellarg($tmp));
@shell_exec($cmd);
if (!filesize($tmp)) { @unlink($tmp); return null; }
$fh=fopen($tmp,'r'); if(!$fh){@unlink($tmp);return null;}
$headers = fgetcsv($fh,0,'|');
if(!$headers){fclose($fh);@unlink($tmp);return null;}
$headers = array_map(fn($h)=>strtolower(trim($h)),$headers);
while(($cols=fgetcsv($fh,0,'|'))!==false){
if ($cols===[null]) continue;
if (count($cols)<count($headers)) $cols=array_pad($cols,count($headers),null);
if (count($cols)>count($headers)) $cols=array_slice($cols,0,count($headers));
$row=@array_combine($headers,$cols) ?: [];
$key=$row['nome_directory'] ?? ($row['internet_cod_stab'] ?? ($row['cod_stabile'] ?? null));
if ((string)$key === $legacyCode){ fclose($fh); @unlink($tmp); return $row; }
}
fclose($fh); @unlink($tmp);
} catch (\Throwable $e) { /* ignore */ }
return null;
}
}