option('stabile-id') ?: 0); $amministratoreId = (int) ($this->option('amministratore-id') ?: 0); $force = (bool) $this->option('force'); if ($stabileId <= 0 && $amministratoreId <= 0) { $this->error('Specificare --stabile-id oppure --amministratore-id'); return self::FAILURE; } $stabileIds = []; if ($stabileId > 0) { $stabileIds = [$stabileId]; } else { $stabileIds = Stabile::query()->where('amministratore_id', $amministratoreId)->pluck('id')->map(fn($v) => (int) $v)->all(); } if (count($stabileIds) < 1) { $this->warn('Nessuno stabile trovato.'); return self::SUCCESS; } $fatture = FatturaElettronica::query() ->whereIn('stabile_id', $stabileIds) ->get(['id', 'stabile_id', 'xml_path', 'p7m_path', 'allegato_pdf_path']); $fatturaIds = $fatture->pluck('id')->map(fn($v) => (int) $v)->all(); $paths = []; foreach ($fatture as $fe) { foreach ([(string) ($fe->xml_path ?? ''), (string) ($fe->p7m_path ?? ''), (string) ($fe->allegato_pdf_path ?? '')] as $p) { $p = trim($p); if ($p !== '') { $paths[$p] = true; } } } $this->line('Target stabili: ' . implode(',', $stabileIds)); $this->line('Fatture elettroniche: ' . count($fatturaIds)); $this->line('File paths (xml/p7m/pdf): ' . count($paths)); if (! $force) { $this->warn('DRY-RUN: aggiungi --force per cancellare davvero.'); return self::SUCCESS; } DB::transaction(function () use ($fatturaIds) { // Documenti protocollati collegati alla FE if (Schema::hasTable('documenti')) { Documento::query() ->where('documentable_type', FatturaElettronica::class) ->whereIn('documentable_id', $fatturaIds) ->delete(); } // Contabilità collegata alla FE if (Schema::hasTable('contabilita_fatture_fornitori')) { $contabIds = DB::table('contabilita_fatture_fornitori') ->whereIn('fattura_elettronica_id', $fatturaIds) ->pluck('id') ->map(fn($v) => (int) $v) ->all(); if (count($contabIds) > 0 && Schema::hasTable('contabilita_fatture_fornitori_righe')) { DB::table('contabilita_fatture_fornitori_righe')->whereIn('fattura_fornitore_id', $contabIds)->delete(); } DB::table('contabilita_fatture_fornitori')->whereIn('fattura_elettronica_id', $fatturaIds)->delete(); } // FE FatturaElettronica::query()->whereIn('id', $fatturaIds)->delete(); }); // Files (best-effort) $deleted = 0; foreach (array_keys($paths) as $path) { try { if (Storage::disk('local')->exists($path)) { Storage::disk('local')->delete($path); $deleted++; } } catch (\Throwable) { // ignore } } $this->info('Cancellazione completata. File eliminati: ' . $deleted); return self::SUCCESS; } }