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

81 lines
3.1 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Fornitore;
use App\Support\ArchivioPaths;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Storage;
class ProvisionFornitoriArchives extends Command
{
protected $signature = 'netgescon:provision-fornitori-archives
{fornitore_id? : ID singolo fornitore}
{--admin-id= : Limita ai fornitori di uno specifico amministratore}
{--all : Esegue su tutti i fornitori}
{--legacy-too : Mostra anche i path legacy annidati sotto amministratori}';
protected $description = 'Crea o riallinea le cartelle archivio dei fornitori esistenti.';
public function handle(): int
{
$query = Fornitore::query()->with('amministratore:id,codice_amministratore,codice_univoco');
$fornitoreId = $this->argument('fornitore_id');
$adminId = (int) $this->option('admin-id');
if ($fornitoreId !== null) {
$query->whereKey((int) $fornitoreId);
} elseif ($adminId > 0) {
$query->where('amministratore_id', $adminId);
} elseif (! $this->option('all')) {
$this->error('Specifica fornitore_id, oppure --admin-id=..., oppure usa --all.');
return self::FAILURE;
}
$processed = 0;
$created = 0;
$query->orderBy('amministratore_id')->orderBy('id')->chunkById(100, function ($fornitori) use (&$processed, &$created): void {
foreach ($fornitori as $fornitore) {
if (! $fornitore instanceof Fornitore) {
continue;
}
$processed++;
$canonicalBase = ArchivioPaths::fornitoreBase($fornitore);
$legacyBase = ArchivioPaths::fornitoreLegacyBase($fornitore);
if (! is_string($canonicalBase) || $canonicalBase === '') {
$this->warn('Saltato fornitore #' . (int) $fornitore->id . ': codice archivio non disponibile.');
continue;
}
$before = Storage::disk('local')->directoryExists($canonicalBase);
$fornitore->ensureArchiveStructure();
$after = Storage::disk('local')->directoryExists($canonicalBase);
if (! $before && $after) {
$created++;
}
$message = '#' . (int) $fornitore->id
. ' ' . trim((string) ($fornitore->ragione_sociale ?: ('Fornitore ' . $fornitore->id)))
. ' -> ' . Storage::disk('local')->path($canonicalBase)
. ' [' . ($after ? ($before ? 'gia_esistente' : 'creata') : 'non_creata') . ']';
$this->line($message);
if ($this->option('legacy-too') && is_string($legacyBase) && $legacyBase !== '') {
$this->line(' legacy: ' . Storage::disk('local')->path($legacyBase) . ' [' . (Storage::disk('local')->directoryExists($legacyBase) ? 'presente' : 'assente') . ']');
}
}
});
$this->info('Provisioning completato. Fornitori processati: ' . $processed . '. Root canonici creati ora: ' . $created . '.');
return self::SUCCESS;
}
}