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

103 lines
3.4 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\Fornitore;
use App\Services\Catalog\FornitoreProductCatalogService;
use Illuminate\Console\Command;
class ImportFornitoreWholesaleCsvCommand extends Command
{
protected $signature = 'fornitore:import-wholesale-csv
{fornitore : ID, P.IVA o ragione sociale del fornitore}
{--csv= : Percorso al CSV listino}
{--limit=0 : Limite righe da importare}
{--dry-run : Simula senza scrivere}';
protected $description = 'Importa un listino CSV fornitore nel catalogo prodotti unificato.';
public function handle(FornitoreProductCatalogService $catalogService): int
{
$fornitore = $this->resolveFornitore((string) $this->argument('fornitore'));
if (! $fornitore instanceof Fornitore) {
$this->error('Fornitore non trovato.');
return self::FAILURE;
}
$csvPath = trim((string) $this->option('csv'));
if ($csvPath === '') {
$this->error('Specificare --csv=/percorso/file.csv');
return self::FAILURE;
}
try {
$stats = $catalogService->importWholesaleCsv(
$fornitore,
$csvPath,
max(0, (int) $this->option('limit')),
(bool) $this->option('dry-run'),
);
} catch (\Throwable $e) {
$this->error($e->getMessage());
return self::FAILURE;
}
$this->table(
['Campo', 'Valore'],
[
['Fornitore', (string) ($fornitore->ragione_sociale ?? ('#' . $fornitore->id))],
['CSV', $csvPath],
['Dry run', (bool) $this->option('dry-run') ? 'si' : 'no'],
['Righe lette', (string) $stats['rows']],
['Prodotti creati', (string) $stats['products']],
['Prodotti aggiornati', (string) $stats['updated']],
['Codici creati', (string) $stats['identifiers']],
['Offerte create/aggiornate', (string) ($stats['offers'] ?? 0)],
['Link sorgente interni', (string) ($stats['private_links'] ?? 0)],
['Media remoti rimossi', (string) ($stats['remote_media_pruned'] ?? 0)],
['Media creati', (string) $stats['media']],
['Righe saltate', (string) $stats['skipped']],
]
);
return self::SUCCESS;
}
private function resolveFornitore(string $value): ?Fornitore
{
$value = trim($value);
if ($value === '') {
return null;
}
$query = Fornitore::query();
if (is_numeric($value)) {
$exact = (clone $query)
->where('id', (int) $value)
->orWhere('partita_iva', $value)
->first();
if ($exact instanceof Fornitore) {
return $exact;
}
}
$exact = (clone $query)
->where('partita_iva', $value)
->orWhere('codice_fiscale', $value)
->first();
if ($exact instanceof Fornitore) {
return $exact;
}
return (clone $query)
->where('ragione_sociale', 'like', '%' . $value . '%')
->orWhere('nome', 'like', '%' . $value . '%')
->orWhere('cognome', 'like', '%' . $value . '%')
->orderBy('ragione_sociale')
->first();
}
}